Java:如何以 ISO 8601 SECOND 格式获取当前日期

2022-01-15 00:00:00 format date timezone java iso

我需要在 ISO 8601 中以 SS 毫秒 和 HH:MM 时区

I need to get the current date in ISO 8601 with SS milliseconds and HH:MM timezone

完整的日期加上小时、分钟、秒和 a 的小数部分第二:YYYY-MM-DDThh:mm:ss.sTZD(例如 1997-07-16T19:20:30.45+01:00)

Complete date plus hours, minutes, seconds and a decimal fraction of a second: YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)

参见:http://www.w3.org/TR/NOTE-datetime

我尝试了不同的方法,但我无法获得正确的毫秒数&时区数字:

i tried different approaches, but i cannot get the correct milliseconds & timezone digits:

DateFormat df=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSZZ");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
df.format(new Date());

JAVA 结果: 2012-11-24T21:19:27.758+0000

JAVA result: 2012-11-24T21:19:27.758+0000

Apache 结果: 2012-11-24T21:19:27.758+00:00(Apache Commons FastDateFormat)

Apache result: 2012-11-24T21:19:27.758+00:00 (Apache Commons FastDateFormat)

推荐答案

其实JDK中有一个类处理ISO8601的解析和格式化:

Actually there is a class in JDK that handles parsing and formatting ISO8601:

import javax.xml.bind.DatatypeConverter;

DatatypeConverter.printDateTime(new GregorianCalendar())
//2012-11-24T22:42:03.142+01:00

相关文章