LocalDate has been added to Java8, which is very convenient. However, java.sql.Date is used when using JDBC, and java.util.Date is used when using POI, but interoperability is not considered in LocalDate. So, for the three that are often used in business, ZonedDateTime also summarized the conversion methods to facilitate interoperability.
sqlDate, utilDate and LocalDate.java
public LocalDate convertToLocalDate(java.sql.Date sqlDate){
return sqlDate.toLocalDate();
}
sqlDate, utilDate and LocalDate.java
public java.util.Date convertToUtilDate(java.sql.Date sqlDate){
return sqlDate;
}
sqlDate, utilDate and LocalDate.java
public LocalDate convertToLocalDate(java.util.Date utilDate){
return utilDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
sqlDate, utilDate and LocalDate.java
public java.sql.Date convertToSqlDate(java.util.Date utilDate){
return new java.sql.Date(utilDate.getTime());
}
sqlDate, utilDate and LocalDate.java
public java.util.Date convertToUtilDate(LocalDate localDate){
return java.util.Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
sqlDate, utilDate and LocalDate.java
public java.sql.Date convertToSqlDate(LocalDate localDate){
return java.sql.Date.valueOf(localDate);
}
sqlDate, utilDate and LocalDate.java
public ZonedDateTime convertToZonedDateTime(java.util.Date utilDate){
return utilDate.toInstant().atZone(ZoneId.systemDefault());
}
sqlDate, utilDate and LocalDate.java
public ZonedDateTime convertToZonedDateTime(java.sql.Date sqlDate){
return sqlDate.toLocalDate().atStartOfDay(ZoneId.systemDefault());
}
sqlDate, utilDate and LocalDate.java
public ZonedDateTime convertToZonedDateTime(LocalDate localDate){
return localDate.atStartOfDay(ZoneId.systemDefault());
}
sqlDate, utilDate and LocalDate.java
public java.util.Date convertToUtilDate(ZonedDateTime zonedDateTime){
return java.util.Date.from(zonedDateTime.toInstant());
}
sqlDate, utilDate and LocalDate.java
public java.sql.Date convertToSqlDate(ZonedDateTime zonedDateTime){
return java.sql.Date.valueOf(zonedDateTime.toLocalDate());
}
sqlDate, utilDate and LocalDate.java
public LocalDate convertToLocalDate(ZonedDateTime zonedDateTime){
return zonedDateTime.toLocalDate();
}
The conversion method of java.util.Date, java.sql.Date, LocalDate, ZonedDateTime is summarized. The source, including the tests, can be found here [https://github.com/xaatw0/quiita/blob/master/src/sqlDate, utilDate and LocalDate.java).
Recommended Posts