87 lines
1.8 KiB
Java
87 lines
1.8 KiB
Java
package org.gcube.application.geoportalcommon.util;
|
|
|
|
import java.time.Instant;
|
|
import java.time.LocalDate;
|
|
import java.time.LocalDateTime;
|
|
import java.time.ZoneId;
|
|
import java.util.Date;
|
|
|
|
/**
|
|
* The Class DateUtils.
|
|
*
|
|
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
|
|
*
|
|
* Aug 4, 2021
|
|
*/
|
|
public class DateUtils {
|
|
|
|
/**
|
|
* As date.
|
|
*
|
|
* @param localDate the local date
|
|
* @return the date
|
|
*/
|
|
public static Date asDate(LocalDate localDate) {
|
|
if (localDate == null)
|
|
return null;
|
|
return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
|
|
}
|
|
|
|
/**
|
|
* As date.
|
|
*
|
|
* @param localDateTime the local date time
|
|
* @return the date
|
|
*/
|
|
public static Date asDate(LocalDateTime localDateTime) {
|
|
if (localDateTime == null)
|
|
return null;
|
|
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
|
|
}
|
|
|
|
/**
|
|
* As local date.
|
|
*
|
|
* @param date the date
|
|
* @return the local date
|
|
*/
|
|
public static LocalDate asLocalDate(Date date) {
|
|
if (date == null)
|
|
return null;
|
|
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
|
|
}
|
|
|
|
/**
|
|
* As local date time.
|
|
*
|
|
* @param date the date
|
|
* @return the local date time
|
|
*/
|
|
public static LocalDateTime asLocalDateTime(Date date) {
|
|
if (date == null)
|
|
return null;
|
|
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
|
|
}
|
|
|
|
public static Date toDate(String date) {
|
|
|
|
if (date == null || date.isEmpty())
|
|
return null;
|
|
|
|
try {
|
|
LocalDate localDate = LocalDate.parse(date);
|
|
return asDate(localDate);
|
|
} catch (Exception e) {
|
|
// TODO: handle exception
|
|
}
|
|
|
|
try {
|
|
LocalDateTime dateTime = LocalDateTime.parse(date);
|
|
return asDate(dateTime);
|
|
} catch (Exception e) {
|
|
// TODO: handle exception
|
|
}
|
|
|
|
return null;
|
|
}
|
|
} |