Java Calendar getTimeInMillis返回错误的时间

时间:2014-09-22 17:59:59

标签: java android calendar

我正在使用适用于Android的Java Calendar类,但是我遇到了一些意想不到的行为。

当我测试以下代码时,它给出了我想要的结果:

Calendar cal = Calendar.getInstance();
cal.getTimeInMillis() - System.currentTimeMillis(); // returns 0 indicating that they are synced

但是当我更改Calendar实例的值时,它似乎不再为getTimeMillis返回正确的值。

例如:

// Current time : 1:56pm

cal.set(Calendar.HOUR, 13);
cal.set(Calendar.MINUTE, 0);

cal.getTimeInMillis();           // returns 1411448454463
System.currentTimeMillis();      // returns 1411407834463

cal.getTimeInMillis() - System.currentTimeMillis();  // returns 40620000

正如您所看到的,cal.getTimeInMillis()返回的数字大于System.currentTimeMillis(),即使时间应该更早(下午1:00对1:56 pm)。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

TL;博士

ZonedDateTime.now(               // Capture the current moment…
    ZoneId.of( "Africa/Tunis" )  // … as seen through the wall-clock time used by the people of a certain region (time zone).
)                                // Returns a `ZonedDateTime` object.
.with(                           // Adjusting…
    LocalTime.of( 13 , 0 )       // …by replacing the time-of-day
)                                // Produces a fresh (second) `ZonedDateTime` object, with values based on the original. Known as Immutable Objects pattern.
.toString()
  

2018-04-24T13:00 + 01:00 [非洲/突尼斯]

java.time

现代方法使用 java.time 类,这些类取代了最初与最早版本的Java捆绑在一起的麻烦的旧日期时间类。

从某个地区的人(time zone)使用的挂钟时间看当前时刻。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

要表示新的所需时间,请使用LocalTime

LocalTime lt = LocalTime.of( 13 , 0 ) ;  // 1 PM.

将现有ZonedDateTime调整为此时间,生成新的ZonedDateTime对象。

ZonedDateTime zdtThirteen = zdt.with( lt ) ;

关于 java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendar和& SimpleDateFormat

现在位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*类。

从哪里获取java.time类?

相关问题