1

I need the format string for a date that is formatted like this: 2017-06-14T00:00:00Z.

Currently, I have:

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

If I parse a the string 2017-06-14T00:00:00Z with this, it gives me the right time in UTC.

But when I take a DateTime object and try to do:

String strNow = new DateTime().toString(DT_SCHEDULE_FORMATTER_START_TIME);

I get something like 2017-06-14T00:00:00 -07:00

I've looked in the documentation and can't seem to find the right formatting string.

Kristy Welsh
  • 7,828
  • 12
  • 64
  • 106
  • **For future visitors of this page:** Check [this answer](https://stackoverflow.com/a/67478337/10819573) for a solution using the modern date-time API. – Arvind Kumar Avinash May 11 '21 at 15:23

3 Answers3

2

That's because the DateTime() constructor uses your system's default timezone, and the Z pattern in the formatter prints the timezone offset.

Your system's default timezone offset is -07:00, that's why you get this output.

If you want exactly the output with Z in the end, you must convert the DateTime object to an org.joda.time.Instant:

String strNow = new DateTime("2017-06-14T00:00:00Z").toInstant().toString();

strNow will be 2017-06-14T00:00:00.000Z.

If you want to get the current time in UTC (instead of parsing a String), you must tell explicity to DateTime constructor to use UTC, using new DateTime(DateTimeZone.UTC).


The code above also prints the milliseconds. If you don't want this, another alternative is to use a DateTimeFormatterBuilder:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendPattern("yyyy-MM-dd'T'HH:mm:ss")
    // append Z if offset is zero (UTC)
    .appendTimeZoneOffset("Z", true, 2, 2)
    // create formatter
    .toFormatter();
String strNow = new DateTime("2017-06-14T00:00:00Z").toInstant().toString(formatter);

This will format the date accordinlgy (without the milliseconds):

2017-06-14T00:00:00Z

1

You can try to use the parseDateTime function

DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
DateTime dateTime = f.parseDateTime("2017-06-14T00:00:00Z");

Hope it will help.

rontho
  • 439
  • 4
  • 11
1

"Z" in format is RFC 822 time zone

For formatting, if the offset value from GMT is 0, "Z" is produced. If the number of pattern letters is 1, any fraction of an hour is ignored.

For parsing, "Z" is parsed as the UTC time zone designator. General time zones are not accepted.

If you want to get string for UTC - you should force timezone:

DateTime dateTime = new DateTime(DateTimeZone.UTC);
String strNow = dateTime.toString(DT_SCHEDULE_FORMATTER_START_TIME);
DeKaNszn
  • 2,720
  • 3
  • 26
  • 26