Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JodaTime DateTime, ISO8601 GMT date format

Tags:

java

jodatime

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! :)

like image 592
Petter Kjelkenes Avatar asked Feb 07 '13 13:02

Petter Kjelkenes


People also ask

What is ISO 8601 date format Java?

The Date/Time API in Java works with the ISO 8601 format by default, which is (yyyy-MM-dd) . All Dates by default follow this format, and all Strings that are converted must follow it if you're using the default formatter.

What is Jodatime?

Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.

How to create new DateTime in Java?

To create a datetime object representing a specific date and time, you may use an initialization string: DateTime dt = new DateTime("2004-12-13T21:39:45.618-08:00"); The initialization string must be in a format that is compatible with the ISO8601 standard.

How do I change the date format in Joda time?

How to change the SimpleDateFormat to jodatime? String s = "2014-01-15T14:23:50.026"; DateTimeFormatter dtf = DateTimeFormat. forPattern("yyyy-MM-dd'T'HH:mm:ss. SSSS"); DateTime instant = dtf.


2 Answers

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); 
like image 172
laz Avatar answered Oct 07 '22 16:10

laz


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

like image 31
petertc Avatar answered Oct 07 '22 17:10

petertc