Reputation: 169
I have a date formatted like this 2018-07-13T16:06:46+00:00. I would like to convert it to long.
I tried the following code and it gives me parse exception.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
Date dt = formatter.parse("2018-07-13T16:06:46+00:00");
Can someone please help?
Thanks.
Upvotes: 1
Views: 337
Reputation: 59950
I would like to convert it to long
It seems you have a problem with the format of your date, If you are using java.time API it can be more easier, you can just use the default format of OffsetDateTime like this :
String stringDate = "2018-07-13T16:06:46+00:00";
OffsetDateTime ofset = OffsetDateTime.parse(stringDate);
Instant instant = ofset.toInstant();
long millisecond = instant.toEpochMilli();
System.out.println(millisecond);//1531498006000
or you can make it in one shot :
//parse the date and convert it to long (It seems you want to get millisecond)
long millisecond = OffsetDateTime.parse("2018-07-13T16:06:46+00:00")
.toInstant()
.toEpochMilli();
Upvotes: 2
Reputation: 4948
This being a standard data format in java 8 you could try:
ZonedDateTime parsedDateTime = ZonedDateTime.parse("2018-07-13T16:06:46+00:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(parsedDateTime.toEpochSecond());
Upvotes: 1
Reputation: 1297
Can verify what @Sun has posted, as I came to the same conclusion. The following code works on my system:
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class DateFormatter {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
try {
Date dt = formatter.parse("2018-07-13T16:06:46+00:00");
System.out.println(dt);
} catch (ParseException e) {
System.out.println(e);
e.printStackTrace();
}
}
}
Upvotes: 0