3
votes

I'm trying to get milliseconds from a date but I got the exception

java.text.ParseException: Unparseable date: "Thu Jul 25 10:56:29 GMT+02:00 2019"

That's what I've done so far:

I took the date from a DatePicker with this pattern "EEE MMM dd HH:mm:ss zzz yyyy" and then passed to a method to get the milliseconds:

long milliDate = parseIso8601(dateTimeCalendar.getTime().toString());

private static long parseIso8601(String value) {
    try {
        return new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US).parse(value).getTime();
    } catch (ParseException ignored) {
        return 0;
    }
}

I got the exception and it returns 0. I don't know what's wrong. Thanks

2
i tried running your same code parseIso8601("Thu Jul 25 10:56:29 GMT+02:00 2019") it is running on my machineNeha Rathore
I cannot reproduce either. Your code runs fine on my desktop Java 11. As an aside consider throwing away the long outmoded and notoriously troublesome SimpleDateFormat and friends, and adding ThreeTenABP to your Android project in order to use java.time, the modern Java date and time API. It is so much nicer to work with.Ole V.V.
The date from your date picker is probably already a Date object. There’s no reason to convert it to a string and parse that string back into a Date. As another aside your method name parseIso8601 is misleading. The format you are parsing has no similarity to ISO 8601.Ole V.V.

2 Answers

6
votes

The problem in zone, zzz expect name of timezone, e.g. EST, GMT or other.

The correct pattern for your case:

EEE MMM dd HH:mm:ss 'GMT'XXX yyyy
0
votes

You can create a Calendar object with the values from your DatePicker and TimePicker:

Calendar calendar = Calendar.getInstance();
calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), 
             timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
long startTime = calendar.getTimeInMillis();