JodaTime DateTime, ISO8601 GMT date format

懵懂的女人 提交于 2019-12-12 08:20:01

问题


How can I get the following format:

2015-01-31T00:00:00Z

(ISO8601 GMT date format)

Out of a DateTime object in joda time (java) ? Eg.

DateTime time = DateTime.now();
String str = // Get something like 2012-02-07T00:00:00Z

Thanks! :)


回答1:


The JODA Javadoc indicates that toString for DateTime outputs the date in ISO8601. If you need to have all of the time fields zeroed out, do this:

final DateTime today = new DateTime().withTime(0, 0, 0, 0);
System.out.println(today);

That will include milliseconds in the output string. To get rid of them you would need to use the formatter that @jgm suggests here.

If you want it to match the format you are asking for in this post (with the literal Z character) this would work:

System.out.println(today.toString(DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")));

If you need the value to be UTC, initialize it like this:

final DateTime today = new DateTime().withZone(DateTimeZone.UTC).withTime(0, 0, 0, 0);



回答2:


@jgm In the document, ISODateTimeFormat.dateTime() is described

Returns a formatter that combines a full date and time, separated by a 'T' (yyyy-MM-dd'T'HH:mm:ss.SSSZZ).

but if you set the timezone, e.g.,

DateTimeFormatter fmt = ISODateTimeFormat.dateTime();  
System.out.println(fmt.print(new DateTime().toDateTime(DateTimeZone.UTC)));

it will ends in Z.




回答3:


use ISODateTimeFormat

DateTime dt = new DateTime();
DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
String str = fmt.print(dt);



回答4:


Set up a DateTimeFormatter:

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
formatter.print(time);


来源:https://stackoverflow.com/questions/14752782/jodatime-datetime-iso8601-gmt-date-format

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