org.springframework.core.convert.support.StringToDateConverter Maven / Gradle / Ivy
package org.springframework.core.convert.support;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
public class StringToDateConverter implements Converter {
protected final Log logger = LogFactory.getLog(getClass());
private boolean context;
@Override
public Date convert(String source) {
if (StringUtils.hasText(source)) {
try {
return Date.from(ZonedDateTime.parse(source).toInstant());
}
catch (DateTimeParseException e) {
// ignore
}
try {
return Date.from(OffsetDateTime.parse(source).toInstant());
}
catch (DateTimeParseException e) {
// ignore
}
ZoneId zoneId = getZoneId();
try {
return Date.from(LocalDateTime.parse(source).atZone(zoneId).toInstant());
}
catch (DateTimeParseException e) {
// ignore
}
try {
return Date.from(LocalDate.parse(source).atTime(LocalTime.now().truncatedTo(ChronoUnit.DAYS)).atZone(zoneId).toInstant());
}
catch (DateTimeParseException e) {
// ignore
}
try {
return Date.from(LocalTime.parse(source).atDate(LocalDate.now()).atZone(zoneId).toInstant());
}
catch (DateTimeParseException e) {
// ignore
}
}
return null;
}
private ZoneId getZoneId() {
return this.context ? LocaleContextHolder.getTimeZone().toZoneId() : ZoneId.systemDefault();
}
public boolean isContext() {
return context;
}
public void setContext(boolean context) {
this.context = context;
}
}