SimpleDateFormat ignores “XXX” if timezone is set to “UTC”

限于喜欢 提交于 2019-12-06 01:58:06

问题


I am trying to output the current datetime as UTC in the following format: 2016-01-11T14:08:42+00:00

final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

final String dateString = formatter.format(new Date());

"dateString" should now contain "2016-01-11T14:08:42+00:00" but it contains "2016-01-11T14:08:42Z".

Without the "UTC" timezone setting I get the right format but - of course - in my specific timezone...

Any ideas?


回答1:


See the documentation for SimpleDateFormat:

For formatting [using an ISO 8601 Time zone], if the offset value from GMT is 0, "Z" is produced.

So, this behaviour is expected.

You can either:

  • Use the RFC 822 timezone formatter ZZZ; however, this produces "+0000"
  • Manipulate the string to replace the final Z: str.replaceAll("Z$", "+00:00")


来源:https://stackoverflow.com/questions/34723683/simpledateformat-ignores-xxx-if-timezone-is-set-to-utc

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