相当于使用一种特殊的方法,一天开始时 http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#atStartOfDay-java.time.ZoneId-, 在课堂里LocalDate http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html:
ZoneId zoneId = ZoneId.of("America/New_York");
ZonedDateTime zdt = LocalDate.now(zoneId).atStartOfDay(zoneId);
另请注意,相当于乔达时间 http://www.joda.org/joda-time/ DateTime http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html is not LocalDateTime http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html, but ZonedDateTime http://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html. The zoneId http://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html参数在这里很重要。迁移的具体示例 - 另请参阅时区网站 http://www.timezoneconverter.com/cgi-bin/zoneinfo?tz=America/Sao_Paulo有关详细信息夏令时 (DST) https://en.wikipedia.org/wiki/Daylight_saving_time巴西的转型:
Joda-Time(旧方式)
DateTime dt =
new DateTime(2015, 10, 18, 12, 0, DateTimeZone.forID("America/Sao_Paulo"));
dt = dt.withTimeAtStartOfDay();
System.out.println(dt); // 2015-10-18T01:00:00.000-02:00
请注意,此代码甚至会在第一行调用午夜抛出异常构造函数 http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#DateTime-int-int-int-int-int-org.joda.time.DateTimeZone-.
java.time(新方式)
ZoneId zoneId = ZoneId.of("America/Sao_Paulo");
ZonedDateTime zdt =
ZonedDateTime.of(2015, 10, 18, 12, 0, 0, 0, zoneId);
zdt = zdt.toLocalDate().atStartOfDay(zoneId);
System.out.println(zdt); // 2015-10-18T01:00-02:00[America/Sao_Paulo]
第二个程序语句的行为与 Joda-Time 不同,因为它不会引发异常,而是默默地将本地时间移动所讨论的间隙大小,此处为一小时。这意味着,如果您选择午夜,结果将是相同的(即 1:00)。如果您选择 00:30,那么结果将为 01:30。上面给出的示例选择中午作为输入。
引用该文档ZonedDateTime.of(...) http://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#of-int-int-int-int-int-int-int-java.time.ZoneId-:
在大多数情况下,本地日期时间只有一个有效的偏移量。在重叠的情况下,当时钟被调回时,有两个有效的偏移。该方法使用通常对应于“夏天”的较早偏移量。
在有间隙的情况下,当时钟向前跳跃时,没有有效的偏移。相反,本地日期时间会根据间隙的长度调整为较晚的时间。对于典型的一小时夏令时更改,本地日期时间将移至一小时后,通常对应于“夏季”的偏移量中。
不可能 100% 迁移所有细节(例如异常行为和应用的 DST 转换策略),因为两个库差异太大。但这是你的指导方针:
- replace
DateTime
by ZonedDateTime
- 考虑切换到
LocalDate
用于中间计算(参见示例)
- 使用对时区的显式引用并替换
DateTimeZone
by ZoneId