0

I have a problem when converting the following ISO string 2017-09-01T01:00:00.000Z into a date.

I'm using SimpleDateFormat as follows

SimpleDateFormat stringToDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date date = stringToDate.parse("2017-09-01T01:00:00.000Z");

The date object output has a date that looks like this

Fri Sep 01 01:00:00 MDT 2017

When I should get an output of

Fri Sep 01 01:00:00 UTC 2017

OR

Fri Aug 31 19:00:00 MDT 2017

It looks like it is not doing the timezone conversion correctly because the time is unchanged, but the timezone has been when neither or both should be changed.

user3331142
  • 1,222
  • 1
  • 11
  • 22
  • 1
    Also dup of [this](http://stackoverflow.com/q/9735426/642706) and [this](http://stackoverflow.com/q/20322545/642706) and [this](http://stackoverflow.com/q/25538918/642706) and many more. – Basil Bourque Mar 29 '17 at 02:47

3 Answers3

2
  1. The single quotes around the 'Z' mean that it's not interpreted as a time zone specifier for UTC: it's simply a literal Z in the string, which is discarded.

    As you are not setting a timezone specifically on the SimpleDateFormat, the date is parsed in your JVM's default timezone.

  2. Date.toString() uses your JVM's default timezone. There is no timezone in a Date. If you want to print in a specific timezone, you need to use a SimpleDateFormat to print it.

Community
  • 1
  • 1
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Thank you. I misunderstood the parsing of SimpleDateFormat. A few stackoverflow answers made it sound like it was telling SimpleDateFormat that it was in UTC. But if it's just discarded, this makes more sense. – user3331142 Mar 28 '17 at 22:40
0

You should use the java.time classes for handling dates in modern Java.

Date doesn't store a timezone, and Date.toString() uses the system default timezone when rendering.

James Fry
  • 1,133
  • 1
  • 11
  • 28
  • I would if I could. Android development is still transitioning over to Java 8 from Java 7 – user3331142 Mar 28 '17 at 22:41
  • You can use joda-time, or the ThreeTenABP project (https://github.com/JakeWharton/ThreeTenABP) to achieve much of the same thing (though they have downsides) – James Fry Mar 28 '17 at 22:44
  • I've debated using Joda just to save me some of the headache of using these old libraries. I'm trying to keep things light on libraries I'm pulling in, but it may be worth it. Thank you – user3331142 Mar 28 '17 at 23:02
0

You could also try this function call to create Calendar instance, it should support yyyy-MM-dd'T'HH:mm:ss.SSSZ format.

Calendar cal = javax.xml.bind.DatatypeConverter.parseDateTime(ymd);

edit: hmm you said Android ok this class may not be available.

Whome
  • 10,181
  • 6
  • 53
  • 65