javaandroidiso8601

Converting ISO 8601-compliant String to epoch on KitKat


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();

Solution

  • 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;
    }