问题
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:
- Use of
Y
instead ofy
: The letterY
specifiesweek-based-year
whereasy
specifiesyear-of-era
. However, I recommend you useu
instead ofy
for the reasons mentioned at `uuuu` versus `yyyy` in `DateTimeFormatter` formatting pattern codes in Java?. You would also like to check this nice answer aboutweek-based-year
. - Enclosing
Z
by single quotes: This is a blunder. The letterZ
specifieszone-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