Converting ISO 8601-compliant String to epoch on KitKat
Asked Answered
L

1

-2

I have the following ISO8601-compliant string:

2024-03-25T11:34:15.000Z

I need to convert it to java Date. I found the following solution:

Date date = Date.from(Instant.parse("2024-03-25T11:34:15.000Z"));
long epoch = date.getTime()); 

However, this requires at least Android Oreo. I need a converter that works down to KitKat. Any idea?

Tried following solutions but had the same issue:

  1. Converting ISO 8601-compliant String to ZonedDateTime
  2. Converting string to date using java8

I also found a solution by using JAXB but I read somewhere that it bloats my APK by 9MB! With it, the solution could be this simple:

javax.xml.bind.DatatypeConverter.parseDateTime(iso8601Date).getTimeInMillis();
Lamkin answered 28/3 at 10:23 Comment(6)
Why not Instant.parse("2024-03-25T11:34:15.000Z").toEpochMilli()?Philologian
Because Instant.parse() requires Android Oreo as well.Lamkin
Well java.time exists because those old classes are buggy. You might like to investigate whether Joda can do it for youPhilologian
Your existing code -- and code using java.time in general -- will work on older Android versions when you use desugaring (or if for some reason you don’t want that, there’s also ThreeTen Android Backport).Armagh
Don’t use Date. In your example code it’s a needless detour. Use just Instant.parse("2024-03-25T11:34:15.000Z").toEpochMillis() to get the milliseconds since the epoch.Armagh
Does this answer your question? Convert String Date to Date in Android (Java/Kotlin) without having to deal with Call requires API level 26Armagh
L
0

This solved my issue.

private long convertDateToLong(@NonNull String iso8601Date) {
    long epoch = -1;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
    try {
        Date date = sdf.parse(iso8601Date);
        if(date != null)
            epoch = date.getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return epoch;
}
Lamkin answered 16/4 at 11:3 Comment(4)
On my desktop Java 19 it fails with java.text.ParseException: Unparseable date: "2024-03-25T11:34:15.000Z".Armagh
In my code, i think i may have used yyyy-MM-dd'T'HH:mm:ss.SSS'Z' instead of yyyy-MM-dd'T'HH:mm:ss.SSSZ. Can't check right now.Lamkin
Never hardcode Z as a literal in your format pattern string. It’s an offset of 0 from UTC and needs to be parsed as an offset, or you will get an incorrect time. I wouldn’t rule out, though, that in the Android version format Z accepts offset 'Z` just to add to the already great confusion caused by the outdated SimpleDateFormat class.Armagh
You're right. I will ask my web endpoint developers to fix this date that they provide to my app. And will update this question and my answer. I feel like it is my responsibility to clarify this question to not mislead other developers.Lamkin

© 2022 - 2024 — McMap. All rights reserved.