getTimeInMillis() returns 相同日期的不同值

getTimeInMillis() returns different values for same dates

我想我没有正确理解 getTimeInMillis()。我一直认为毫秒时间戳代表一个日期,但就我而言,这让我有了不同的想法。在这里,我使用一种方法向数组添加时间戳,如下所示:

Calendar date = Calendar.getInstance();
date.set(2015, 9, 25, 12, 0);
timeArray.push(date.getTimeInMillis());

在代码的其他部分,我在同一日期做同样的事情:

Calendar date2 = Calendar.getInstance();
date2.set(2015, 9, 25, 12, 0);

很遗憾,这个比较returns false:

timeArray.get(0) == date2.getTimeInMillis();

这两个值不应该是真的吗?或者我理解错了 getTimeInMillis() 方法?如果是这样,我怎样才能以其他方式实现我想要做的事情?

我们来看看documenation
所以根据 set 方法的文档:

Sets the values for the calendar fields YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY, and MINUTE. Previous values of other fields are retained. If this is not desired, call clear() first.

所以修复应该很简单:只需先调用 clear() 方法。

不可变对象

by Timofey is correct. This demonstrates the problems that come with the old date-time classes being highly mutable. In contrast, the alternatives, java.time and Joda-Time, both use immutable objects。在此模式中,新对象是基于原始对象实例化的,而不是改变原始对象。

java.time

这是 java.time 中的一些示例代码 Java 8. Instant is a moment on the timeline in UTC while ZonedDateTime is an Instant adjusted into a time zone (ZoneId).

一块一块地建造一个ZonedDateTimedate, time,zone.

LocalDate datePortion = LocalDate.of ( 2015 , 9 , 25 );
LocalTime timePortion = LocalTime.NOON;
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.of ( datePortion , timePortion , zoneId );

通过首先访问 ZonedDateTime.

中的 Instant 从纪元中提取毫秒数
Instant instant = zdt.toInstant ();
long millisecondsSinceEpoch = instant.toEpochMilli ();  // WARNING: Data loss. The java.time types have nanosecond resolution.

走向另一个方向。 注意: 这涉及可能的数据丢失。 java.time框架使用的分辨率nanoseconds, 9 digits of fractional second. Milliseconds只有3位小数秒

Instant instantFromMillis = Instant.ofEpochMilli ( millisecondsSinceEpoch );

转储到控制台。

System.out.println ( "Date: " + datePortion + " Time: " + timePortion + " in zoneId: " + zoneId + " is " + zdt + " with milliseconds since epoch: " + millisecondsSinceEpoch );

当运行.

Date: 2015-09-25 Time: 12:00 in zoneId: America/Montreal is 2015-09-25T12:00-04:00[America/Montreal] with milliseconds since epoch: 1443196800000