javaandroidtimedowngrade

How to downgrade java.time code in older Android?


I've got this neat code which generates a list of days between two dates, and then the date of the current day, as well as its position in the list (Most importantly, all the dates are in the same format, which makes it easy to compare them).

//Create list of days
String s = "2018-08-28";
String e = "2018-09-05";
LocalDate start = LocalDate.parse(s);
LocalDate end = LocalDate.parse(e);
List<LocalDate> totalDates = new ArrayList<>();
while (!start.isAfter(end)) {
    totalDates.add(start);
    start = start.plusDays(1);
}

//Date and place of current day
LocalDate a = LocalDate.now();
int current_day = totalDates.indexOf(a) + 1;

The problem is that while I was playing with this code in a Java IDE, I did not know that some of its parts (.parse() ; .now() ; .isAfter() ; .plusDays()) were reserved for 26+ level API phones. Or, the maximum API in which my application should work is API 23.

I want to know how I can "downgrade" it in the most efficient way, and I don't know what to do or where to start.


Solution

  • Back-port

    No need to "downgrade". Most of the java.time functionality has been back-ported.

    Add the ThreeTen-Backport library to your probject, adapted for Android specifically in the ThreeTenABP project. See links below, at bottom.

    The legacy date-time classes are an awful ugly mess — never use them.

    By the way, those textual formats to which you referred are standard, defined in ISO 8601. The java.time classes use these formats by default when parsing/generating strings.


    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

    You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

    Where to obtain the java.time classes?