我有一个日期以字符串格式 ddMMyyyy 和 hh:mm 和 TimeZone 存储在数据库中。我想根据这些信息创建一个 Instant,但我不知道该怎么做。
就像是
LocalDateTime dateTime = LocalDateTime.of(2017, Month.JUNE, 1, 13, 39);
Instant instant = dateTime.toInstant(TimeZone.getTimeZone("ECT"));
您可以先ZonedDateTime
使用该时区创建一个,然后调用toInstant
:
LocalDateTime dateTime = LocalDateTime.of(2017, Month.JUNE, 15, 13, 39);
Instant instant = dateTime.atZone(ZoneId.of("Europe/Paris")).toInstant();
System.out.println(instant); // 2017-06-15T11:39:00Z
我还改用了完整的时区名称(根据 Basil 的建议),因为它不那么模棱两可。
忘记旧的 TimeZone 类。使用ZoneId
,因为它是正确的线程安全的,您可以只使用最终静态字段来存储区域。
LocalDateTime dateTime = LocalDateTime.of(2017, Month.JUNE, 1, 13, 39);
ZonedDateTime.of(dateTime, ZoneId.of("ECT")).toInstant();
我认为以下代码应该可以工作:
LocalDateTime time = LocalDateTime.of(2017, Month.JUNE, 15, 13, 39);
ZonedDateTime.of(time, TimeZone.getTimeZone("ZONE").toZoneId()).toInstant();
您只需将“ZONE”替换为您需要的时区。