问题:是否需要配置时区?不配置默认使用系统时间所在时区
只支持JDK8日期类型LocalDate,LocalTime,LocalDateTime
示例
标准用法:@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
不建议使用: @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
配置
注意:
- FormattingConversionService 不支持DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
- 必须按标准规则DateTimeFormatter.ofPattern("yyyy-MM-ddTHH:mm:ss")
- @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 仍继续支持
@Configuration
public class TimeConfig {
@Bean
public FormattingConversionService conversionService() {
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(true);
// 确保@NumberFormat仍支持
conversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());
// @DateTimeFormat全局配置
DateTimeFormatterRegistrar deserialization = new DateTimeFormatterRegistrar();
//ISO_LOCAL_DATE 等于 DateTimeFormatter.ofPattern("yyyy-MM-dd")
deserialization.setDateFormatter(DateTimeFormatter.ISO_LOCAL_DATE);
//ISO_LOCAL_TIME 等于 DateTimeFormatter.ofPattern("HH:mm:ss")
deserialization.setTimeFormatter(DateTimeFormatter.ISO_LOCAL_TIME);
//ISO_LOCAL_DATE_TIME 等于 DateTimeFormatter.ofPattern("yyyy-MM-ddTHH:mm:ss")
deserialization.setDateTimeFormatter(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
deserialization.registerFormatters(conversionService);
return conversionService;
}
/**
* JsonFormat全局配置
*
* @return Module
*/
@Bean
public Module timeModule() {
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ISO_LOCAL_DATE));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ISO_LOCAL_TIME));
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
return javaTimeModule;
}
}