如何将UTC日期时间转换为Java中的ISO 8601格式? [英] how to convert UTC date-time into ISO 8601 format in Java?

查看:467
本文介绍了如何将UTC日期时间转换为Java中的ISO 8601格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以特定的ISO 8601格式设置UTC日期时间,例如 2020-02-28T14:10:23 + 00:00 ,而不是 2020-02-28T14: 10:23Z 。我不希望Z结尾但+00:00。我尝试了 simpleDateFormat文档并且似乎没有格式可以提供上述格式。

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.

这是我尝试过的Java代码,

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()));

可以通过在格式化的字符串中用+00:00替换z来实现,但这不是似乎是一个不错的选择。

It could be achieved by replacing z with +00:00 in the formatted string but it doesn't seems to be a good option.

推荐答案

根据 DateTimeFormatter


Offset X and x (偏移X和x ):这将根据模式字母的数量来格式化偏移量。除非分钟非零,否则一个字母仅输出小时,例如 +01,在这种情况下,分钟也会输出,例如 +0130。两个字母输出小时和分钟,不带冒号,例如 +0130。 三个字母输出小时和分钟,并带有冒号,例如 +01:30 。四个字母输出小时和分钟,可选秒,不带冒号,例如 +013015。五个字母输出小时和分钟,可选秒,并带有冒号,例如 +01:30:15。六个或更多字母会引发IllegalArgumentException。当要输出的偏移量为零时,模式字母 X(大写)将输出 Z,而模式字母 x(小写)将输出 +00, + 0000或 +00:00

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'.

尝试使用 xxx ,例如:

DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx").format(ZonedDateTime.now())

返回类似


2020-02-28T12:42:30+00:00


基于Java版本13,使用 jshell OpenJDK 13测试; DateTimeFormatter 在Java 8或更高版本中可用

Based on Java version 13, tested with jshell OpenJDK 13; DateTimeFormatter is available in Java 8 or later

这篇关于如何将UTC日期时间转换为Java中的ISO 8601格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆