Reputation: 41
I have String s1 as below.
String s1 = "2021-10-12T14:28:46.615+00:00"
I want to convert it to exact same java.util.Date instance - 2021-10-12T14:28:46.615+00:00
Using below is returning "2021-10-12T14:38:15.000-0400"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss");
Date d1 = dateFormat.parse(s1);
And using below is throwing parsing error
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sssZ");
Date d1 = dateFormat.parse(s1);
Pls advice the dateformat I should be using
Upvotes: 0
Views: 358
Reputation: 40034
Here is one way if you must use the legacy (and deprecated) Date class. But you should focus on using the java.time package.
String s1 = "2021-10-12T14:28:46.615+00:00";
OffsetDateTime odt = OffsetDateTime.parse(s1);
long epochMilli = odt.toInstant().toEpochMilli();
Date date = new Date(epochMilli);
System.out.println(date);
prints
Tue Oct 12 10:28:46 EDT 2021
Note that since the offset is +00:00
the timezone is for UTC/Greenwich
and adjusted accordingly. If required, you can use .plusHours()
or .minusHours()
on the value returned by parse
to adjust the offset based on locality.
Upvotes: 1