如何将Timestamp转换为LocalDateTime保留时区?

问题描述 投票:0回答:1

如何将Timestamp转换为LocalDateTime保留时区?

我尝试使用TimestampObject.toLocalDateTime().toLocalDate()但是这不保留时区。

java datetime java-8 timezone timestamp
1个回答
2
投票

您应该使用正确的数据类型在数据库中存储时间戳。根据您的确切要求和RDBMS的功能,这可能是例如用于MS的timestamp with time zonedatetimeoffset。然后从Java存储OffsetDateTime或只是Instant对象进入数据库并检索相同类型的背面。 OffsetDateTime被称为,因为除了日期和时间之外,它还有一个偏移量。它的方法toLocalDateTimetoLocalDate保留了偏移量,因为它们给出的时间和日期与原始偏移量一致。 LocalDateLocalDateTime都不能自己保留偏移或时区。如果可以的话,避免长期过时的java.sql.Timestamp课程。

您的字符串包括-0800,与UTC的偏移量,然后是UTC,通常意味着从UTC偏移0,但在这种情况下可能意味着前者偏移量来自UTC。我希望你知道,因为我没有。偏移量与时区不同:时区包含其所代表的位置的所有历史和已知的偏移变化。

假设您的数据库已经包含字符串(例如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();

我考虑到字符串包含小写的ampm,其中Java通常期望大写,通过解析该位不敏感,我检查文本UTC是否存在,但不要用于任何事情。该片段产生OffsetDateTime2018-01-30T17:17-08:00,接下来是LocalDate2018-01-30

© www.soinside.com 2019 - 2024. All rights reserved.