我在数据库中以字符串格式ddMMyyyy和hh:mm以及时区存储了一个日期。我想根据这些信息创建一个Instant对象,但是我不知道怎么做。
类似以下的方式:
LocalDateTime dateTime = LocalDateTime.of(2017, Month.JUNE, 1, 13, 39);
Instant instant = dateTime.toInstant(TimeZone.getTimeZone("ECT"));
ZonedDateTime
,然后调用toInstant
方法:
您可以先使用该时区创建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的建议改用完整的时区名称,因为这样更清晰明了。
ZoneId.of( "America/Guayaquil" )
来代替。 - Basil BourqueEurope/Paris
),所以我可以理解为什么使用全名会更好;) - Jorn VerneeOffsetDateTime
来确定一个时刻:OffsetDateTime.of(LocalDate.of(2018, 1, 23), LocalTime.MIN, ZoneOffset.UTC)
。 - Basil Bourque不要再使用旧的TimeZone类,而应该使用ZoneId
,因为它是线程安全的,您可以使用一个final静态字段来存储时区。
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”即可。
ZonedDateTime.ofInstant(instant, TimeZone.getDefault())
吗? - soorapadman大陆/地区
,例如Europe/London
,Europe/Paris
,Asia/Kolkata
,Pacific/Auckland
。如果你所指的“ECT”是指厄瓜多尔时间,请使用ZoneId.of("America/Guayaquil")
。如果你所指的是中欧时间,请使用适当的Europe/...
时区名称。 - Basil BourqueTIMESTAMP WITH TIME ZONE
(正如你应该做的)。日期时间列没有“格式”,因为它们不是字符串/文本。将日期时间值作为日期时间对象而不是字符串检索出来。Instant instant = myResultSet.getObject( … , Instant.class );
- Basil Bourque