出于测试目的,我想创建一个固定Clock时区:
Clock c= Clock.fixed(Instant.parse("2018-04-29T10:15:30.00Z"), ZoneId.of("Europe/Berlin"));
//yields FixedClock[2018-04-29T10:15:30Z,Europe/Berlin]
Run Code Online (Sandbox Code Playgroud)
现在我想使用Clock智慧LocalDateTime:
LocalDateTime.now(c);
//yields 2018-04-29T12:15:30
Run Code Online (Sandbox Code Playgroud)
为什么我要偏移两个小时?有没有 UTC 转换的地方?我需要做什么才能生成固定的Clock时区并LocalDate.now(c)产生相同的时间?
2018-04-29T10:15:30.00Z 对应于 2018-04-29T12:15:30+02:00 并且LocalDateTime从中OffsetDateTime给出 2018-04-29T12:15:30; 你的LocalDateTime.now(c).
演示:
import java.time.*;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.parse("2018-04-29T10:15:30.00Z");
ZoneId zoneId = ZoneId.of("Europe/Berlin");
Clock c= Clock.fixed(instant, zoneId);
// 2018-04-29T10:15:30.00Z corresponds to 2018-04-29T12:15:30+02:00
OffsetDateTime odt = instant.atZone(zoneId).toOffsetDateTime();
System.out.println(odt);
// LocalDateTime from this OffsetDateTime results in 2018-04-29T12:15:30
System.out.println(odt.toLocalDateTime());
// So does LocalDateTime.now(c)
System.out.println(LocalDateTime.now(c));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
2018-04-29T12:15:30+02:00
2018-04-29T12:15:30
2018-04-29T12:15:30
Run Code Online (Sandbox Code Playgroud)
您需要使用 UTC 偏移量来获取LocalDateTime与给定值相同的Instant。
演示:
import java.time.*;
public class Main {
public static void main(String[] args) {
Clock c = Clock.fixed(Instant.parse("2018-04-29T10:15:30.00Z"), ZoneId.of("Europe/Berlin"));
LocalDateTime ldt = Instant.now(c).atZone(ZoneOffset.UTC).toLocalDateTime();
System.out.println(ldt);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
2018-04-29T10:15:30
Run Code Online (Sandbox Code Playgroud)
从Trail: Date Time了解现代日期时间 API 。
| 归档时间: |
|
| 查看次数: |
292 次 |
| 最近记录: |