Search code examples
javadatetimejava-timethreetenbp

Convert java.time classes from java 8 to java 5


What do I do to use this lines of code with Java 5, as this code runs with Java 6 and 7 using threetenbp and runs on Java 8 directly:

// start date (set the time to start of day)
ZonedDateTime from = LocalDate.parse("2017-07-05").atStartOfDay(ZoneOffset.UTC);
// end date (set the time to 11 PM)
ZonedDateTime to = LocalDate.parse("2017-07-08").atTime(23, 0).atZone(ZoneOffset.UTC);

// get start and end timestamps
long start = from.toInstant().truncatedTo(ChronoUnit.MINUTES).toEpochMilli() / 1000;
long end = to.toInstant().truncatedTo(ChronoUnit.MINUTES).toEpochMilli() / 1000;

Solution

  • The ThreeTen Backport seems to work only in Java 6 and 7. I've tested with JDK 5 and it throws an UnsupportedClassVersionError.

    In Java 5, one alternative is the old SimpleDateFormat and Calendar classes:

    // set the formatter to UTC
    TimeZone utc = TimeZone.getTimeZone("UTC");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    sdf.setTimeZone(utc);
    
    // parse and set the time to midnight
    Calendar cFrom = Calendar.getInstance(utc);
    cFrom.setTime(sdf.parse("2017-07-05"));
    cFrom.set(Calendar.HOUR_OF_DAY, 0);
    cFrom.set(Calendar.MINUTE, 0);
    cFrom.set(Calendar.SECOND, 0);
    cFrom.set(Calendar.MILLISECOND, 0);
    
    // parse and set the time to 23:00
    Calendar cTo = Calendar.getInstance(utc);
    cTo.setTime(sdf.parse("2017-07-08"));
    cTo.set(Calendar.HOUR_OF_DAY, 23);
    cTo.set(Calendar.MINUTE, 0);
    cTo.set(Calendar.SECOND, 0);
    cTo.set(Calendar.MILLISECOND, 0);
    
    // get the epoch second (get millis and divide by 1000)
    long start = cFrom.getTimeInMillis() / 1000;
    long end = cTo.getTimeInMillis() / 1000;
    

    The other alternative is to use Joda-Time, which has an API very similar to java.time:

    import org.joda.time.DateTime;
    import org.joda.time.DateTimeZone;
    import org.joda.time.LocalDate;
    import org.joda.time.LocalTime;
    
    DateTime from = LocalDate.parse("2017-07-05").toDateTimeAtStartOfDay(DateTimeZone.UTC);
    DateTime to = LocalDate.parse("2017-07-08").toDateTime(new LocalTime(23, 0), DateTimeZone.UTC);
    
    long start = from.getMillis() / 1000;
    long end = to.getMillis() / 1000;
    

    This will produce the same values for start and end.


    Just a note: Joda-Time is in maintainance mode and is being replaced by the new APIs, so I don't recommend start a new project with it (unless you can't use the new API's, of course).
    Even in joda's website it says: "Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).".