Reputation: 6862
I am trying to convert string to ZonedDateTime.
I have tried following:
SimpleDateFormat zonedDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
zonedDateTimeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
long timeMs = zonedDateTimeFormat.parse("2017-07-18T20:26:28.582+03:00[Asia/Istanbul]").getTime();
It gives java.text.ParseException: Unparseable date
How can I parse the following string into ZonedDateTime
2017-07-18T20:26:28.582+03:00[Asia/Istanbul]
Upvotes: 2
Views: 2755
Reputation: 78935
java.time
API with the error-prone, java.util
and java.text
date-time APIIn March 2014, Java 8 introduced the modern, java.time
date-time API which supplanted the error-prone legacy, java.util
and java.text
date-time API. Any new code should use the java.time
API*.
Given below is the excerpt from ZonedDateTime#parse
documentation:
Obtains an instance of ZonedDateTime from a text string such as 2007-12-03T10:15:30+01:00[Europe/Paris]. The string must represent a valid date-time and is parsed using DateTimeFormatter.ISO_ZONED_DATE_TIME.
Since your text string, 2017-07-18T20:26:28.582+03:00[Asia/Istanbul] fully complies with the default format, you do not need to specify any DateTimeFormatter
explicitly.
Demo:
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.parse("2017-07-18T20:26:28.582+03:00[Asia/Istanbul]");
System.out.println(zdt);
}
}
Output:
2017-07-18T20:26:28.582+03:00[Asia/Istanbul]
Learn more about the modern Date-Time API from Trail: Date Time.
If you are receiving an instance of java.util.Date
, convert it tojava.time.Instant
, using Date#toInstant
and derive other date-time classes of java.time
from it as per your requirement.
Upvotes: 2
Reputation: 11739
For ZonedDateTime we need to use ZonedDateTime.parse
method with DateTimeFormatter
. If I am not wrong you have an ISO
date:
ZonedDateTime zonedDateTime = ZonedDateTime.parse(
"2017-07-18T20:26:28.582+03:00[Asia/Istanbul]",
DateTimeFormatter.ISO_DATE_TIME
);
System.out.println(zonedDateTime); //2017-07-18T20:26:28.582+03:00[Asia/Istanbul]
You can use either ISO_ZONED_DATE_TIME
or ISO_DATE_TIME
. Both are able to parse a date-time with offset and zone.
Upvotes: 2
Reputation: 3881
The java.time
API has many inbuilt-formats that simplify parsing and formatting process. The String you are trying to parse is in the standard ISO_ZONED_DATE_TIME format. So, you could parse it easily in the following way and then get the milliseconds from the epoch:
DateTimeFormatter formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME ;
ZonedDateTime zdt = ZonedDateTime.parse(
"2017-07-18T20:26:28.582+03:00[Asia/Istanbul]",
formatter); // prints 2017-07-18T20:26:28.582+03:00[Asia/Istanbul]
long timeInMs = zdt.toInstant().toEpochMilli();
Upvotes: 3
Reputation: 25573
ZonedDateTime.parse
seems to be designed to handle the exact string you provided. There is no need to go through the old SimpleDateFormat
Upvotes: 2