问题
I want to format a UTC date-time in a specific ISO 8601 format like 2020-02-28T14:10:23+00:00 but not 2020-02-28T14:10:23Z. I don't want Z at the end but +00:00. I tried all the formats in simpleDateFormat doc and no format seems to give the above-mentioned one.
I know both represents same time irrespective of the format but it needs to be formatted like that for backward compatibility reasons.
Here is the java code that I tried,
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(new Date()));
It could be achieved by replacing z with +00:00 in the formatted string but it doesn't seems to be a good option.
回答1:
According documentation of DateTimeFormatter
Offset X and x: This formats the offset based on the number of pattern letters. One letter outputs just the hour, such as '+01', unless the minute is non-zero in which case the minute is also output, such as '+0130'. Two letters outputs the hour and minute, without a colon, such as '+0130'. Three letters outputs the hour and minute, with a colon, such as '+01:30'. Four letters outputs the hour and minute and optional second, without a colon, such as '+013015'. Five letters outputs the hour and minute and optional second, with a colon, such as '+01:30:15'. Six or more letters throws IllegalArgumentException. Pattern letter 'X' (upper case) will output 'Z' when the offset to be output would be zero, whereas pattern letter 'x' (lower case) will output '+00', '+0000', or '+00:00'.
Try with xxx
like in:
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx").format(ZonedDateTime.now())
which returns something like
2020-02-28T12:42:30+00:00
Based on Java version 13, tested with jshell
OpenJDK 13; DateTimeFormatter
is available in Java 8 or later
来源:https://stackoverflow.com/questions/60451547/how-to-convert-utc-date-time-into-iso-8601-format-in-java