我需要知道,在java(我的版本jdk 8)中,我可以替换,new DateTime(System.currentTimeMillis())
这个代码形式,'DateTime.now()
'?
我用过包import org.joda.time.DateTime;
如何在java 8中写出同样的东西(日期和时间)?
java.time.Instant.now() // Capture the current moment in UTC.
在内部,由于1970-01-01T00:00:00Z的时期参考(Z
表示UTC),该时刻被跟踪为整秒的计数加上小数秒作为纳秒的计数。
您的DateTime
课程显然来自Joda-Time图书馆。该库的创建者Stephen Colebourne继续使用JSR 310中的Java 8及更高版本内置的java.time类替换Joda-Time。
Instant
在UTC中,请使用Instant
。要捕获UTC中的当前时刻,Instant.now()
。
Instant
表示自UTC 1970年第一时刻的纪元参考以来的纳秒数。
对System.currentTimeMillis()
的调用是相同的,自1970年UTC开始以来的计数,除了更粗略的毫秒而不是纳秒的分辨率。实际上,传统的计算机时钟无法准确地跟踪当前时刻(以纳秒为单位),因此使用Instant
捕获当前时刻可能只捕获微秒(典型地在Java 9及更高版本中)或毫秒(在Java 8中)。
结果:没有必要打电话给System.currentTimeMillis()
。请改用Instant.now()
。
ZonedDateTime
相当于DateTime
将是ZonedDateTime
。此类表示通过特定区域(时区)的人使用的挂钟时间看到的时刻。
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
在Java 8中,DateTime maps to java.time.ZonedDateTime
和java.time.OffsetDateTime
。
本页面由Joda Time的创建者/作者/维护者撰写,建议:
如果您在Java SE 8中编写代码,那么它的时间是迁移到java.time ...
是。 new DateTime(System.currentTimeMillis())
将致电
public DateTime(long instant) {
super(instant);
}
然后
public BaseDateTime(long instant) {
this(instant, ISOChronology.getInstance());
}
和DateTime.now()
会打电话
public static DateTime now() {
return new DateTime();
}
然后
public DateTime() {
super();
}
然后
public BaseDateTime() {
this(DateTimeUtils.currentTimeMillis(), ISOChronology.getInstance());
}
这与第一种方式相同。
是。
这是相关代码:
public BaseDateTime() {
this(DateTimeUtils.currentTimeMillis(), ISOChronology.getInstance());
}
public BaseDateTime(long instant) {
this(instant, ISOChronology.getInstance());
}