1970 年之前的 java/android 毫秒?

Milliseconds in java/android before 1970?

我知道如何获取 1.1.1970 之后的日期的毫秒数。但是我怎样才能得到在那个日期之前发生的特定日期的毫秒数呢? 我在 android 应用程序中需要它。 谢谢!

所有数字都在 java 中签名,因此所有数字都可以为负数。因此你可以有一个负数毫秒的日期。因此,时间戳小于 0 的日期绝对是可能的。

您可以通过执行以下操作了解最早的可能日期:

new Date(Long.MIN_VALUE)

你会发现这个 returns 是一个超过 2.92 亿年前的日期。这甚至在侏罗纪时代之前。所以真的没有必要担心 1970 年之前的日期:)

使用 java.time.Instant,在 Instant 中获取您的日期,您可以使用 getEpochSecond() 方法 return 纪元之前的秒数,然后从中转换。

https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html 了解有关 Instant 的更多详细信息 class。

tl;博士

LocalDate.of( 1953 , 1 , 17 )
         .atStartOfDay( ZoneId.of( "America/Montreal" ) )
         .toInstant()
         .toEpochMilli()

…产生一个负数:

-535057200000

详情

正如其他答案所说:

(a) 在将时刻表示为count-from-epoch-reference-date时,纪元之前的时刻使用负数,纪元之后的时刻使用正数。

(b) 您应该使用 java.time 类 而不是麻烦的旧 date-time 类,它们现在已经是遗留问题了。有关 back-port 到 Android.

的信息,请参阅下文

使用java.time

使用 LocalDate 作为 date-only 值,没有 time-of-day 也没有时区。

LocalDate ld = LocalDate.of( 1953 , 1 , 17 );

要转换为时刻,让我们获取该日期当天的第一个时刻。这意味着指定一个时区,因为全球各地的日期因时区而异。应用 ZoneId 以获得 ZonedDateTime 对象。

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ld.atStartOfDay( z );

提取 InstantUTC 时间轴上的一个时刻。

Instant instant = zdt.toInstant();

Instant 中提取自 1970 年第一个时刻以来的毫秒数(UTC(1970-01-01T00:00:00Z))。当心 data-loss,因为 java.time 类 可以保持分辨率高达 nanoseconds; asking for milliseconds 的瞬间,这意味着如果存在任何纳秒,它就会消失。

long epochMillis = instant.toEpochMilli();

看到这个 code run line in IdeOne.com

ld.toString(): 1953-01-17

zdt.toString(): 1953-01-17T00:00-05:00[America/Montreal]

instant.toString(): 1953-01-17T05:00:00Z

epochMillis: -535057200000


关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time project, now in maintenance mode, advises migration to the java.time 类.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

在哪里获取java.time类?

  • Java SE 8 and SE 9 及更高版本
    • Built-in。
    • 标准 Java API 的一部分,带有捆绑实施。
    • Java 9 添加了一些小功能和修复。
  • Java SE 6 and SE 7
  • Android
    • ThreeTenABP项目专门为Android改编ThreeTen-Backport(上面提到的)。
    • 参见

这个问题是我无法重现的。在 1.1.1970 之前,这些值为负数。现在,我的程序计算正确,但我认为,我没有更改代码中的某些内容。可能是缓存版本导致了问题。感谢大家的回答!