Reputation: 41099
I'm trying to parse the following string to a Date
object:
2013-12-26T01:00:56.664Z
Using this SimpleDateFormat
:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
But I'm getting a:
java.text.ParseException: Unparseable date: "2013-12-26T01:00:56.664Z" (at offset 19)
What am I doing wrong, How I should handle the T
and the Z
letters in the date?
Upvotes: 6
Views: 231
Reputation: 78975
java.time
In March 2014, Java 8 introduced the modern, java.time
date-time API which supplanted the error-prone legacy java.util
date-time API. Any new code should use the java.time
API.
On a side note, never specify 'Z'
in a date-time parsing/formatting pattern because 'Z'
is a character literal while Z
is a pattern character specifying time zone offset. To parse a string representing a time zone offset, you must use X
(or XX
or XXX
depending on the requirement).
Since your date-time string is in the default format used by Instant#parse
, you can parse it to an Instant
directly.
Demo:
import java.time.Instant;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.parse("2013-12-26T01:00:56.664Z");
System.out.println(instant);
}
}
Output:
2013-12-26T01:00:56.664Z
Note: For whatever reason, if you need an instance of java.util.Date
from this object of Instant
, you can do so as follows:
java.util.Date date = Date.from(instant);
Learn more about the modern date-time API from Trail: Date Time.
Upvotes: 2
Reputation: 4476
The real isssue with the date is not T & Z but the milliseconds.
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
This must be the format that is to be used becaue there are milli seconds as well in the input date.
Upvotes: 5
Reputation: 276
You can use this
String date = "2013-12-26T01:00:56.664Z";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
try {
System.out.println(sdf.parse(date)); // Result Thu Dec 26 01:00:56 CET 2013
} catch (ParseException e) {
e.printStackTrace();
}
Upvotes: 0