此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.6

配置全局日期和时间格式

默认情况下,日期和时间字段未使用@DateTimeFormat从 strings 结合使用DateFormat.SHORT风格。如果您愿意,可以通过以下方式更改此设置 定义您自己的全局格式。

为此,请确保 Spring 不注册默认格式化程序。相反,请注册 格式化程序:

例如,以下配置会注册一个全局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 转换和格式化


APP信息