Warm tip: This article is reproduced from serverfault.com, please click

java-如何解析格式yyyy-MM-ddTHH:mm:ss.SSS + ZZZZ的UTC时间戳

(java - How to parse UTC timestamp of format yyyy-MM-ddTHH:mm:ss.SSS+ZZZZ)

发布于 2020-12-03 16:15:48

我有时间戳2020-12-03T05:35:59.398+0000String格式是在流式批处理中接收的。

我只想2020-12-03 05:35:59作为java.sql.Timestamp实例,以便能够将其与其他Timestamp实例进行比较

Timestamp.valueOf()函数出现以下错误

Exception in thread "main" java.time.format.DateTimeParseException : Text '2020-12-03T05:35:59.398+0000' could not be parsed at index 23

我尝试了此处给出的答案,并且确实发生了转换,但是时间更改为2020-12-03 11:05:59

我尝试过在此处给定的格式之间进行更改,但仍然没有解决方案。

+两者之间是否还有时间戳记格式398+0000

Questioner
DrthSprk_
Viewed
11
Ole V.V. 2020-12-04 15:27:40

java.time

我建议你使用java.time(现代的Java日期和时间API)进行日期和时间工作。

    DateTimeFormatter isoFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxx");
    DateTimeFormatter sqlTimestampFormatter = new DateTimeFormatterBuilder()
            .append(DateTimeFormatter.ISO_LOCAL_DATE)
            .appendLiteral(' ')
            .append(DateTimeFormatter.ISO_LOCAL_TIME)
            .toFormatter();
    
    String aTimestampString = "2020-12-03T05:35:59.398+0000";
    String anotherTimestampString = "2020-12-04 06:43:58.556385";
    
    Instant anInstant = isoFormatter.parse(aTimestampString, Instant::from);
    Instant anotherInstant = LocalDateTime.parse(anotherTimestampString, sqlTimestampFormatter)
            .atOffset(ZoneOffset.UTC)
            .toInstant();
    
    if (anInstant.isBefore(anotherInstant)) {
        System.out.println(aTimestampString + " is earlier");
    } else {
        System.out.println(anotherTimestampString + " is earlier");
    }

此示例的输出是:

2020-12-03T05:35:59.398 + 0000是更早的

+0000前串以上是从UTC的偏移-的00时00分偏移。由于它为零,因此我们知道时间以UTC为单位。我不知道其他字符串的时区或UTC偏移量。你需要知道,否则你将得到错误的结果。在上面的代码中,我假设其他字符串也位于UTC中。

不要使用时间戳记

我尝试了此处给出的答案,但确实发生了转换,但时间更改为 2020-12-03 11:05:59

这是令人困惑的Timestamp类。你获得了正确的时间戳记值。会发生什么事,当你打印Timestamp对象,是你(或明或暗地)调用它的toString方法。Timestamp.toString()混淆地使用了JVM的默认时区来呈现字符串。因此,如果你的时间戳等于2020-12-03T05:35:59.398 UTC,并且你的时区是例如Asia / Kolkata,则时间将转换为Asia / Kolkata时区,并2020-12-03 11:05:59返回并打印字符串

你没有什么好用的老式java.sql.Timestamp类。它最初的目的是在带有和不带有时区的时间戳值与SQL数据库之间来回传递。从JDBC 4.2开始,我们更喜欢使用OffsetDateTimeInstantLocalDateTime为此目的。所以就算Timestamp上课了。

关联

Oracle教程:Date Time说明如何使用java.time。