parse String to 'yyyy-mm-ddThh:mm:ss.SSSZ' ISODate java

11,261

Solution 1

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

Solution 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);
Share:
11,261
Yoga
Author by

Yoga

Updated on June 04, 2022

Comments

  • Yoga
    Yoga almost 2 years

    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.

    • s7vr
      s7vr over 7 years
      What is your java version ?
    • Ole V.V.
      Ole V.V. over 7 years
      Is your time zone always Z? If not, what other things could it be?
    • Ole V.V.
      Ole V.V. over 7 years
      Java 8 java.time is great for ISO dates and times. It seems to me that Instant.parse() would eat your string without a problem. If your MongoDB driver doesn’t accept an Instant, converting to Date is easy.
    • Basil Bourque
      Basil Bourque over 7 years
    • Yoga
      Yoga over 7 years
      I am using java 7
  • Ole V.V.
    Ole V.V. over 7 years
    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).
  • s7vr
    s7vr over 7 years
    I have checked already. I don't think there is one for MongoDB.
  • Yoga
    Yoga over 7 years
    I am using JDK 1.7