springboot时间日期格式化转换,支持Date、LocalDateTime类型

2023-02-17· 614 次浏览
MVC接收参数时的日期解析 ```java package cn.itsub.manghe.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.format.Formatter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; /** * MVC接收参数时的日期解析 */ @Configuration public class DateFormatConfig { static final String DataTimePattern = "yyyy-MM-dd HH:mm:ss"; static final String DataPattern = "yyyy-MM-dd"; @Bean public Formatter<LocalDateTime> localDateTimeFormatter() { return new Formatter<LocalDateTime>() { @Override public String print(LocalDateTime localDate, Locale locale) { return DateTimeFormatter.ofPattern(DataTimePattern,locale).format(localDate); } @Override public LocalDateTime parse(String s, Locale locale) { return LocalDateTime.parse(s,DateTimeFormatter.ofPattern(DataTimePattern,locale)); } }; } @Bean public Formatter<LocalDate> localDateFormatter() { return new Formatter<LocalDate>() { @Override public String print(LocalDate localDate, Locale locale) { return DateTimeFormatter.ofPattern(DataPattern,locale).format(localDate); } @Override public LocalDate parse(String s, Locale locale) { return LocalDate.parse(s,DateTimeFormatter.ofPattern(DataPattern,locale)); } }; } @Bean public Formatter<Date> dateFormatter() { SimpleDateFormat df = new SimpleDateFormat(DataTimePattern); return new Formatter<Date>() { @Override public String print(Date date, Locale locale) { return df.format(date); } @Override public Date parse(String s, Locale locale) throws ParseException { return df.parse(s); } }; } } ```