Monday, January 22, 2018

How to handle LocalDate/LocalTime in code of JDK 6

Question: I'm writing a library and it has some code like:
    public void foo(Object value){
      if(value instanceof Date){
          ...
      }else if(value instanceof Calendar){
          ...
      }...
    }
The code is supposed can be running on at lease JDK6. So, I have to code and compile on JRE6. But, in case, if a user works on JDK8 and passing a LocalDate/LocalTime object to the method.
How should I handle the case?
LocalDate/LocalTime can't compile on JRE6.
Or, I have to use two version of code? One for JDK6, and another for JDK8?
Answer:
1->Certainly you can't use your JDK 8 types in your JDK 6 code base. However, you may consider using JDK 6 types in your JDK 8 code base. For example, you could consider using 310-backports which basically provides the same set of classes in JDK 8 java.time API for applications running in earlier versions of Java. Unfortunately, this also means changing your JDK8-based APIs to use this backports. –
2->Here's a utility class I use to convert the newer java.time classes to java.util.Date objects and vice versa:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class DateUtils {

  public static Date asDate(LocalDate localDate) {
    return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
  }

  public static Date asDate(LocalDateTime localDateTime) {
    return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
  }

  public static LocalDate asLocalDate(Date date) {
    return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
  }

  public static LocalDateTime asLocalDateTime(Date date) {
    return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
  }
}

No comments:

Post a Comment

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...