0
String timeString = "2016-02-18T20:15:37.421Z";

How do I convert this into Date object? I tried something like this

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeString = "2016-02-18T20:15:37.421Z";
Date date= dateFormat.parse(timeString);

That gives me an Unparseable date exception

developer747
  • 15,419
  • 26
  • 93
  • 147

1 Answers1

2

We just need to change the date format to yyyy-MM-dd'T'HH:mm:ss.SSS, e.g.:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
String timeString = "2016-02-18T20:15:37.421Z";
Date date;
try {
        date = dateFormat.parse(timeString);
        System.out.println(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
  • That worked! Thank you! I will mark it as soon as it lets me. – developer747 Mar 12 '16 at 01:55
  • I don't think that this works if the time zone is not UTC. See also [ISO 8601 time zone designators](https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators). – Mick Mnemonic Mar 12 '16 at 02:02
  • Format `yyyy-MM-dd'T'HH:mm:ss.SSSZ` would also take the time zone offset into account. – Mick Mnemonic Mar 12 '16 at 02:06
  • And it would fail for example in question :) – Darshan Mehta Mar 12 '16 at 02:07
  • Sorry, my bad. `yyyy-MM-dd'T'HH:mm:ss.SSSX` would be the correct format; using the pattern for [ISO-8601 time zone](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html#iso8601timezone) (`Z` is for [RFC-822 time zone](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html#rfc822timezone)). – Mick Mnemonic Mar 12 '16 at 02:17