DateTimeFormatter issue

折月煮酒 提交于 2021-02-10 15:15:19

问题


See the following test code (java 11):

public static final String DATE_FORMAT_TIMESTAMP = "YYYY-MM-dd'T'HH:mm:ss'Z'";
...
var timestamp = OffsetDateTime.now();
System.out.println(timestamp);

var formatter = DateTimeFormatter.ofPattern(DATE_FORMAT_TIMESTAMP);
var zt = timestamp.format(formatter);
System.out.println(zt);
...

The output:enter code here

2020-12-27T23:34:34.886272600+02:00
2021-12-27T23:34:34Z

Note formatted time year is 2021. And it happens only from 27/12, probably till 31/12.

Can someone explain this to me? And how do I fix the code to get the correct formatted string?


回答1:


There are two problems with your pattern:

  1. Use of Y instead of y: The letter Y specifies week-based-year whereas y specifies year-of-era. However, I recommend you use u instead of y for the reasons mentioned at `uuuu` versus `yyyy` in `DateTimeFormatter` formatting pattern codes in Java?. You would also like to check this nice answer about week-based-year.
  2. Enclosing Z by single quotes: This is a blunder. The letter Z specifies zone-offset and if you enclose it by single quotes, it will simply mean the literal, Z.

Check the documentation page of DateTimeFormatter to learn more about these things.

A quick demo:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        final String DATE_FORMAT_TIMESTAMP = "uuuu-MM-dd'T'HH:mm:ssZ";
        // OffsetDateTime now with the default timezone of the JVM
        var timestamp = OffsetDateTime.now();
        System.out.println(timestamp);

        var formatter = DateTimeFormatter.ofPattern(DATE_FORMAT_TIMESTAMP);
        var zt = timestamp.format(formatter);
        System.out.println(zt);

        // OffsetDateTime now with the timezone offset of +02:00 hours
        timestamp = OffsetDateTime.now(ZoneOffset.of("+02:00"));
        System.out.println(timestamp);
        zt = timestamp.format(formatter);
        System.out.println(zt);

        // Parsing a user-provided date-time
        String strDateTime = "2020-12-27T23:34:34.886272600+02:00";
        timestamp = OffsetDateTime.parse(strDateTime);
        System.out.println(timestamp);
        zt = timestamp.format(formatter);
        System.out.println(zt);
    }
}

Output:

2020-12-27T23:44:35.531145Z
2020-12-27T23:44:35+0000
2020-12-28T01:44:35.541700+02:00
2020-12-28T01:44:35+0200
2020-12-27T23:34:34.886272600+02:00
2020-12-27T23:34:34+0200



回答2:


That's because of the uppercase YYYY. You need yyyy here.

Y means week year. That is the year to which the week number belongs. For example, 27 Dec 2020 is week 1 of 2021.



来源:https://stackoverflow.com/questions/65470770/datetimeformatter-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!