3.6配置全局Date和Time格式

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

为此,你需要确保Spring不注册默认格式化程序。相反,你应该手动注册所有格式化程序。使用org.springframework.format.datetime.joda.JodaTimeFormatterRegistrar或org.springframework.format.datetime.DateFormatterRegistrar 类,具体取决于是否使用Joda-Time 库。

例如,下面的Java配置注册一个全局yyyYMdD格式(这个示例不依赖于JoDA时间库):

@Configuration
public class AppConfig {

    @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 date conversion with a specific global format
        DateFormatterRegistrar registrar = new DateFormatterRegistrar();
        registrar.setFormatter(new DateFormatter("yyyyMMdd"));
        registrar.registerFormatters(conversionService);

        return conversionService;
    }
}

如果你更喜欢XML配置, 那么可以使用FormattingConversionServiceFactoryBean,如下所示(使用joda time):

Joda-Time提供单独的不同类型来表示date、time和date-time值。应使用JodTimeFormatterRegStrar的DateFormatter、TimeFormatter和DateTimeFormatter属性为每种类型配置不同的格式。DateTimeFormatterFactoryBean提供了一种创建格式化程序的方便方法。

如果使用SpringMVC,请记住显式配置所使用的转换服务。对于基于Java的@Configuration,这意味着扩展WebMvcConfigurationSupport类并重写mvcConversionService()方法。对于XML,应该使用mvc:annotation-driven元素的conversion-service属性。有关详细信息,请参见转换和格式化。

最后更新于

这有帮助吗?