配置全局日期和时间格式
默认情况下,未用 @DateTimeFormat 注解的日期和时间字段将使用 DateFormat.SHORT 样式从字符串转换。如果您愿意,可以通过定义自己的全局格式来更改此设置。
为此,请确保 Infra 不注册默认格式化程序。相反,请借助以下类手动注册格式化程序:
-
infra.format.datetime.standard.DateTimeFormatterRegistrar -
infra.format.datetime.DateFormatterRegistrar
例如,以下配置注册了一个全局 yyyyMMdd 格式:
@Configuration
public class ApplicationConfiguration {
@Bean
public FormattingConversionService conversionService() {
// 使用 DefaultFormattingConversionService 但不注册默认值
DefaultFormattingConversionService conversionService =
new DefaultFormattingConversionService(false);
// 确保仍然支持 @NumberFormat
conversionService.addFormatterForFieldAnnotation(
new NumberFormatAnnotationFormatterFactory());
// 使用特定的全局格式注册 JSR-310 日期转换
DateTimeFormatterRegistrar dateTimeRegistrar = new DateTimeFormatterRegistrar();
dateTimeRegistrar.setDateFormatter(DateTimeFormatter.ofPattern("yyyyMMdd"));
dateTimeRegistrar.registerFormatters(conversionService);
// 使用特定的全局格式注册日期转换
DateFormatterRegistrar dateRegistrar = new DateFormatterRegistrar();
dateRegistrar.setFormatter(new DateFormatter("yyyyMMdd"));
dateRegistrar.registerFormatters(conversionService);
return conversionService;
}
}
请注意,在 Web 应用程序中配置日期和时间格式时还有其他注意事项。请参阅 WebMVC 转换和格式化。