配置全局日期和时间格式

默认情况下,未用@DateTimeFormat注解的日期和时间字段使用DateFormat.SHORT样式从字符串转换。如果需要,可以通过定义自己的全局格式来更改此设置。

为此,请确保 Spring 不注册默认格式化程序。相反,请使用以下方法手动注册格式化程序:

  • org.springframework.format.datetime.standard.DateTimeFormatterRegistrar

  • org.springframework.format.datetime.DateFormatterRegistrar

例如,以下配置注册了一个全局的yyyyMMdd格式

@Configuration
public class ApplicationConfiguration {

	@Bean
	public FormattingConversionService conversionService() {

		// Use the DefaultFormattingConversionService but do not register defaults
		DefaultFormattingConversionService conversionService =
				new DefaultFormattingConversionService(false);

		// Ensure @NumberFormat is still supported
		conversionService.addFormatterForFieldAnnotation(
				new NumberFormatAnnotationFormatterFactory());

		// Register JSR-310 date conversion with a specific global format
		DateTimeFormatterRegistrar dateTimeRegistrar = new DateTimeFormatterRegistrar();
		dateTimeRegistrar.setDateFormatter(DateTimeFormatter.ofPattern("yyyyMMdd"));
		dateTimeRegistrar.registerFormatters(conversionService);

		// Register date conversion with a specific global format
		DateFormatterRegistrar dateRegistrar = new DateFormatterRegistrar();
		dateRegistrar.setFormatter(new DateFormatter("yyyyMMdd"));
		dateRegistrar.registerFormatters(conversionService);

		return conversionService;
	}
}

请注意,在 Web 应用程序中配置日期和时间格式时,还有一些额外的注意事项。请参阅WebMVC 转换和格式化WebFlux 转换和格式化