如何将 Timestamp
转换为 LocalDateTime
并保留时区?
我尝试使用 TimestampObject.toLocalDateTime().toLocalDate()
但这不会保留时区。
最佳答案
您确实应该使用正确的数据类型在数据库中存储时间戳。根据您的具体要求和 RDBMS 的功能,这可能是 MS 的timestamp with time zone
或 datetimeoffset
。然后从 Java 将 OffsetDateTime
或仅 Instant
对象存储到数据库中并检索相同类型。 OffsetDateTime
之所以这样称呼,是因为除了日期和时间之外,它还保存着偏移量。其方法 toLocalDateTime
和 toLocalDate
保留偏移量,因为它们给出的时间和日期与原始偏移量一致。 LocalDate
和 LocalDateTime
本身都不能保存偏移量或时区。如果可以的话,请避免使用过时的 java.sql.Timestamp
类。
您的字符串包括 -0800
(相对于 UTC 的偏移量),然后是 UTC
,这通常意味着相对于 UTC 的偏移量 0,但在本例中可能意味着前者偏移量来自 UTC。我希望你知道,因为我不知道。偏移量与时区不同:时区包含其所代表的位置的所有历史和已知的 future 偏移量变化。
假设您的数据库已经包含字符串(例如 varchar
),您可以从它们中获取日期、时间和偏移量,如下所示:
DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder()
.appendPattern("d-MMM-uuuu h:mm ")
.parseCaseInsensitive()
.appendPattern("a")
.parseCaseSensitive()
.appendPattern(" xx 'UTC'")
.toFormatter(Locale.ROOT);
String timestampString = "30-Jan-2018 5:17 pm -0800 UTC someText";
ParsePosition pos = new ParsePosition(0);
OffsetDateTime dateTime
= OffsetDateTime.from(timestampFormatter.parse(timestampString, pos));
LocalDate date = dateTime.toLocalDate();
我考虑到该字符串包含小写的 am
或 pm
,而 Java 通常会期望大写,通过不区分大小写地解析该位,并且我检查文本 UTC
就在那里,但不要将其用于任何用途。该代码段生成 OffsetDateTime
为 2018-01-30T17:17-08:00
,然后生成 LocalDate
为 2018-01- 30
.
关于java - 如何将 Timestamp 转换为 LocalDateTime 保留时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48629221/