29

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

Petter Kjelkenes
  • 1,605
  • 1
  • 19
  • 25

4 Answers4

46

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);
laz
  • 28,320
  • 5
  • 53
  • 50
  • 1
    Should there be a second single quote after `:ss'Z"` ? – spuder Dec 22 '15 at 00:06
  • What happens if the string has an offset in it, i need to parse the string to get a date time without an offset ' DateTime today = new DateTime("2016-07-11T05:04:30-05:30"); System.out.println(today.toString(DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss")));'gives a result like this "2016-07-11T05:34:30" where the mins field is altered @petter kjelkenes – Gowrav Jul 13 '16 at 16:49
  • @spuder Yes. A single quote is missing in the answer after Z. – Sunil Kumar Sep 04 '17 at 06:44
9

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

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
petertc
  • 3,607
  • 1
  • 31
  • 36
5

use ISODateTimeFormat

DateTime dt = new DateTime();
DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
String str = fmt.print(dt);
mantrid
  • 2,830
  • 21
  • 18
  • Note that ISODateTimeFormat.dateTime() ends in ZZ not Z. There's a difference (ZZ prepends a colon). –  Feb 07 '13 at 14:10
  • Although it's absolutely not clear what exactly petter is asking about, your example differs from his example: It includes milliseconds in the output and uses the default time zone instead of UTC. – jarnbjo Feb 07 '13 at 14:36
3

Set up a DateTimeFormatter:

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