Java 使用日期而不是时间戳
我的代码:Java 使用日期而不是时间戳,java,date,Java,Date,我的代码: Calendar calendar = DateProvider.getCalendarInstance(TimeZone.getTimeZone("GMT")); calendar.setTime(date); calendar.set(Calendar.YEAR, 1970); calendar.set(Calendar.MONTH, Calendar.JANUARY); calendar.set(Calendar.DATE, 1);
Calendar calendar = DateProvider.getCalendarInstance(TimeZone.getTimeZone("GMT"));
calendar.setTime(date);
calendar.set(Calendar.YEAR, 1970);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DATE, 1);
date = calendar.getTime();
Timestamp epochTimeStamp = new Timestamp(date.getTime());
我想在这种情况下消除时间戳的使用,如何在不使用java.sql.Timestamp的情况下使用epochTimeStamp实现同样的效果?我需要的格式与使用时间戳时的格式相同。因为您需要
日期的字符串
表示,然后使用将日期
对象转换为字符串
:
Calendar calendar = ...
//...
date = calendar.getTime();
Timestamp epochTimeStamp = new Timestamp(date.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
System.out.println(sdf.format(date));
System.out.println(sdf.format(epochTimeStamp));
} catch (Exception e) {
//handle it!
}
根据您的示例,打印
01/01/1970 09:21:18
01/01/1970 09:21:18
这将为您提供与时间戳格式相同的历元时间:
public class FormatDate {
public static void main(String[] args) {
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd kk:mm:ss:SSS");
LocalDateTime datetime = LocalDateTime.of(1970, 1, 1, 0, 0);
System.out.println(datetime.format(format));
}
}
在Java中表示日期时间对象的另一种方法是使用Joda时间库
import org.joda.time.LocalDate;
...
LocalDate startDate= new LocalDate();//"2014-05-06T10:59:45.618-06:00");
//or DateTime startDate = new DateTime ();// creates instance of current time
String formatted =
startDate.toDateTimeAtCurrentTime().toString("MM/dd/yyy HH:mm:ss");
使用这些库进行格式化、设置和获取时间有几种方法,它们比使用JDK日期和日历库更可靠。这些也将在hibernate/JPA中保持。如果没有其他选择,希望这能给你选择 如果您正在谈论编写日期的字符串
表示形式的格式,则应使用SimpleDataFormat
。您对时间戳做了什么?我们不知道您所说的“需要格式相同”是什么意思。你能澄清一下吗?时间戳给我:1970-01-01 00:00:00.007日期给Thu Jan 01 00:00:00 UTC 1970我必须使用我稍后在代码中返回的时间戳来检查它是否在某个时间范围内。然后你说的是日期的字符串表示。。。