com.geotab.model.serialization.DateTimeSerializationUtil Maven / Gradle / Ivy
/*
*
* 2020 Copyright (C) Geotab Inc. All rights reserved.
*/
package com.geotab.model.serialization;
import java.time.Clock;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
@UtilityClass
public class DateTimeSerializationUtil {
private static final String DATETIME_INPUT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
private static final String DATE_INPUT_PATTERN = "yyyy-MM-dd";
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter
.ofPattern(DATETIME_INPUT_PATTERN)
.withChronology(IsoChronology.INSTANCE);
private static final DateTimeFormatter DATE_TIME_PARSE_FORMATTER = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.optionalStart()
.appendOffset("+HH", "Z")
.optionalEnd()
.toFormatter();
private static DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_INPUT_PATTERN)
.withChronology(IsoChronology.INSTANCE);
public static LocalDateTime localDateTimeFromString(String dateTimeString) {
if (StringUtils.isEmpty(dateTimeString)) {
return null;
}
if (!dateTimeString.contains("T")) {
dateTimeString += "T00:00:00.000Z";
}
return LocalDateTime.parse(dateTimeString, DATE_TIME_PARSE_FORMATTER);
}
public static String localDateTimeToString(LocalDateTime dateTime) {
if (dateTime == null) {
return null;
}
return dateTime.format(DATE_TIME_FORMATTER);
}
public static LocalDate localDateFromString(String dateString) {
if (StringUtils.isEmpty(dateString)) {
return null;
}
return LocalDate.parse(dateString, DATE_FORMATTER);
}
public static String localDateToString(LocalDate localDate) {
if (localDate == null) {
return null;
}
return localDate.format(DATE_FORMATTER);
}
public static LocalDateTime nowUtcLocalDateTime() {
return LocalDateTime.now(Clock.systemUTC());
}
public static LocalDateTime localDateTimeToUtc(LocalDateTime localDateTime) {
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
ZonedDateTime utcZoned = zonedDateTime.withZoneSameInstant(ZoneId.of("UTC"));
return utcZoned.toLocalDateTime();
}
}