Changing Java Timestamp format causes a change of the timestamp

后端 未结 2 1312
轻奢々
轻奢々 2020-12-07 05:49

I\'m a bit puzzled regarding the Java timestamp formatting functions as they seem to change the timestamp by a few minutes.

My Pivotal CloudFoundry app writes a new

2条回答
  •  借酒劲吻你
    2020-12-07 06:01

    First, I was really puzzled and thought, you might have found some kind of bug in SimpleDateFormat. Your code can be reduced to the following lines to show the same behaviour:

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSS");
    String str = "2018-06-18 13:07:27.624828+02";
    System.out.println(str);
    System.out.println(format.parse(str));
    

    Result:

    2018-06-18 13:07:27.624828+02
    Mon Jun 18 13:17:51 CEST 2018
    

    The parsed Date object got ten additional minutes (and some seconds).

    Taking a closer look reveals the problem - it is NOT a bug in JDK:

    Your millisecond-part is 624828 - these are six(!) digits (not three). 624828 milliseconds are about 624 seconds, which are 10 minutes and 24 seconds. The SimpleDateFormat correctly summed up this additional seconds and minutes.

    What's wrong too: Your date format contains five digits for the milliseconds part.

    Solution:

    The (new) Java Time API can handle larger fractions of a second - and also convert easily between different time zones:

    String str = "2018-06-18 13:07:27.624828+02";
    DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSx");
    OffsetDateTime date = OffsetDateTime.parse(str, pattern);
    System.out.println(date);
    System.out.println(date.withOffsetSameInstant(ZoneOffset.UTC));
    

    Result:

    2018-06-18T13:07:27.624828+02:00
    2018-06-18T11:07:27.624828Z
    

提交回复
热议问题