跳到主要内容
版本:7.0.3

配置全局日期和时间格式

Hunyuan 7b 中英对照 Configuring a Global Date and Time Format

默认情况下,未使用@DateTimeFormat标注的日期和时间字段会使用DateFormat.SHORT格式从字符串进行转换。如果您愿意,可以通过定义自己的全局格式来更改这一设置。

为此,请确保Spring不会注册默认的格式化器。相反,需要借助以下方法手动注册格式化器:

  • org.springframework.format.datetime.StandardDateTimeFormatter Registrar

  • 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转换与格式化