parse String to 'yyyy-mm-ddThh:mm:ss.SSSZ' ISODate java
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);
Yoga
Updated on June 04, 2022Comments
-
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 over 7 yearsWhat is your java version ?
-
Ole V.V. over 7 yearsIs your time zone always
Z
? If not, what other things could it be? -
Ole V.V. over 7 yearsJava 8
java.time
is great for ISO dates and times. It seems to me thatInstant.parse()
would eat your string without a problem. If your MongoDB driver doesn’t accept anInstant
, converting toDate
is easy. -
Basil Bourque over 7 yearsAlso duplicate of Parsing ISO 8601 date format like 2015-06-27T13:16:37.363Z in Java.
-
Yoga over 7 yearsI am using java 7
-
-
Ole V.V. over 7 yearsA new JDBC driver should accept an
Instant
without it having been converted toDate
(don’t know if such a new driver exists for MongoDB, nor whether the asker has got one, though). -
s7vr over 7 yearsI have checked already. I don't think there is one for MongoDB.
-
Yoga over 7 yearsI am using JDK 1.7