1

How to convert String to ISODate format using SimpleDateFormat, which means that i want to finally get Date in java.util.Date format.

My string will look like 2017-02-17T09:28:03.000Z, i want to convert it to date formt. I can do this in Joda date format, but since i am using mongoDB, it does not accept joda format.

   String startDateString1 =  "2017-02-17T04:23:17.452Z";      
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 
    Date  startDate = df.parse(startDateString1);
    String newDateString = df.format(startDate);

above code is not working.

Yoga
  • 293
  • 3
  • 8
  • 23

3 Answers3

3

Your code is not working since Z is a reserved character used to interpret RFC-822 time zones :

RFC 822 time zone: For formatting, the RFC 822 4-digit time zone format is used:

 RFC822TimeZone:
         Sign TwoDigitHours Minutes
 TwoDigitHours:
         Digit Digit

Since Java 7, you can use X to interpret ISO-8601 time zones https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html . The following works :

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");

However, on my computer,

System.out.println(newDateString);

results in the following output :

2017-02-17T05:23:17.452+01

Alternatively, if you are sure to have only UTC dates, you could escape the Z letter with simple quotes :

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

And here is the displayed result :

2017-02-17T04:23:17.452Z

Emmanuel Guiton
  • 1,315
  • 13
  • 24
2

You can do it in Java 8 like below.

Instant instant = Instant.parse("2017-02-17T09:28:03.000Z");
Date date = Date.from(instant);
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • A new JDBC driver should accept an `Instant` without it having been converted to `Date` (don’t know if such a new driver exists for MongoDB, nor whether the asker has got one, though). – Ole V.V. Feb 17 '17 at 13:50
  • 1
    I have checked already. I don't think there is one for MongoDB. – s7vr Feb 17 '17 at 13:53
  • I am using JDK 1.7 – Yoga Feb 20 '17 at 05:33
0

You could use javax.xml.bind.DatatypeConverter.parseDateTime("2017-02-17T04:23:17.452Z") which will return a Calendar object. You can call getTime() on it to get a Date object.

mwstc013
  • 86
  • 3