java中的方法 DateTime.now() 和 new DateTime(System.currentTimeMillis()) 是否相同?

uma*_*uma 1 java datetime date jodatime java-time

我需要知道,在java(我的版本jdk 8)中,我可以替换,new DateTime(System.currentTimeMillis())这个代码形式,' DateTime.now()'?

我用过包import org.joda.time.DateTime;

如何在java 8中写同样的东西(日期和时间)?

Bas*_*que 6

太长了;博士

java.time.Instant.now()  // Capture the current moment in UTC. 
Run Code Online (Sandbox Code Playgroud)

在内部,自纪元参考 1970-01-01T00:00:00Z(即 UTC)以来,该时刻以整秒计数加上小数秒(纳秒计数)的形式进行跟踪Z

java.time

您的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

相当于。DateTimeZonedDateTime此类代表通过特定地区(时区)的人们使用的挂钟时间看到的时刻。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Run Code Online (Sandbox Code Playgroud)

  • “即时”并不代表“UTC 中的某个时刻”。它代表一个时间点,完全不受时区的影响。 (2认同)