org.springframework.format.datetime.DateFormatterCustom Maven / Gradle / Ivy
package org.springframework.format.datetime;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Locale;
import org.springframework.context.i18n.LocaleContextHolder;
/**
* Date 포맷
*/
public final class DateFormatterCustom extends DateFormatter {
private boolean threadLocal;
@Override
protected DateFormat getDateFormat(Locale locale) {
DateFormat dateFormat = super.getDateFormat(locale);
if (this.threadLocal) {
dateFormat.setTimeZone(LocaleContextHolder.getTimeZone());
}
return dateFormat;
}
/**
* "\\d{4}-\\d{2}-\\d{2}"
* (?:[01]\\d|2[0123]):(?:[012345]\\d):(?:[012345]\\d)
* DateFormatter#setIso(ISO.DATE_TIME)
* DateFormatter#setIso(ISO.DATE)
* yyyy-MM-dd'T'HH:mm:ss.SSS'Z'XXX
* @see com.fasterxml.jackson.databind.util.ISO8601Utils#parse(String, ParsePosition)
*/
@Override
public Date parse(String text, Locale locale) throws ParseException {
try {
return super.parse(text, locale);
}
catch (ParseException e) {
try {
return Date.from(OffsetDateTime.parse(text).toInstant());
}
catch (DateTimeParseException exception) {
e.addSuppressed(exception);
}
try {
return Date.from(LocalDateTime.parse(text).atZone(ZoneId.systemDefault()).toInstant());
}
catch (DateTimeParseException exception) {
e.addSuppressed(exception);
}
try {
return Date.from(LocalDate.parse(text).atTime(LocalTime.now().truncatedTo(ChronoUnit.DAYS)).atZone(ZoneId.systemDefault()).toInstant());
}
catch (DateTimeParseException exception) {
e.addSuppressed(exception);
}
try {
return Date.from(LocalTime.parse(text).atDate(LocalDate.now()).atZone(ZoneId.systemDefault()).toInstant());
}
catch (DateTimeParseException exception) {
e.addSuppressed(exception);
}
throw e;
}
}
public boolean isThreadLocal() {
return threadLocal;
}
public void setThreadLocal(boolean threadLocal) {
this.threadLocal = threadLocal;
}
}