shz.core.time.ToLocalDateTime Maven / Gradle / Ivy
package shz.core.time;
import shz.core.NullHelp;
import java.sql.Timestamp;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
public final class ToLocalDateTime {
private ToLocalDateTime() {
throw new IllegalStateException();
}
private static DateTimeFormatter[] FORMATTERS = {
TimeHelp.DATE_TIME_PATTERN,
TimeHelp.DATE_TIME_PATTERN2,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"),
DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"),
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"),
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
};
public static void setFormatters(DateTimeFormatter[] formatters) {
if (NullHelp.nonEmpty(formatters)) FORMATTERS = formatters;
}
public static LocalDateTime from(Timestamp timestamp) {
return timestamp == null ? null : timestamp.toLocalDateTime();
}
public static LocalDateTime from(ZonedDateTime zdt) {
return zdt == null ? null : zdt.toLocalDateTime();
}
public static LocalDateTime from(Instant instant) {
return instant == null ? null : Timestamp.from(instant).toLocalDateTime();
}
public static LocalDateTime from(Long timestamp) {
return timestamp == null ? null : Timestamp.from(Instant.ofEpochMilli(timestamp)).toLocalDateTime();
}
public static LocalDateTime from(LocalDate ld) {
return ld == null ? null : LocalDateTime.of(ld, LocalTime.MIN);
}
public static LocalDateTime from(Date date) {
return date == null ? null : Timestamp.from(Instant.ofEpochMilli(date.getTime())).toLocalDateTime();
}
static LocalDateTime from(String s) {
for (DateTimeFormatter formatter : FORMATTERS) {
try {
return LocalDateTime.parse(s, formatter);
} catch (DateTimeParseException ignored) {
}
}
return null;
}
public static LocalDateTime from(CharSequence cs) {
if (NullHelp.isBlank(cs)) return null;
String s = cs.toString();
LocalDateTime result;
if ((result = from(s)) != null) return result;
if ((result = from(ToTimestamp.from(s))) != null) return result;
if ((result = from(ToZonedDateTime.from(s))) != null) return result;
if ((result = from(ToInstant.from(s))) != null) return result;
if ((result = from(ToLong.from(s))) != null) return result;
if ((result = from(ToLocalDate.from(s))) != null) return result;
return null;
}
public static LocalDateTime from(Object obj) {
if (obj == null) return null;
if (obj instanceof LocalDateTime) return (LocalDateTime) obj;
if (obj instanceof Timestamp) return from((Timestamp) obj);
if (obj instanceof ZonedDateTime) return from((ZonedDateTime) obj);
if (obj instanceof Instant) return from((Instant) obj);
if (obj instanceof Long) return from((Long) obj);
if (obj instanceof LocalDate) return from((LocalDate) obj);
if (obj instanceof Date) return from((Date) obj);
if (obj instanceof CharSequence) return from((CharSequence) obj);
return null;
}
}