Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

datetime - how to convert UTC date-time into ISO 8601 format in Java?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...