設定全域日期和時間格式

預設情況下,未使用 @DateTimeFormat 註解的日期和時間欄位會使用 DateFormat.SHORT 樣式從字串轉換而來。如果您願意,可以透過定義自己的全域格式來變更此設定。

若要執行此操作,請確保 Spring 不會註冊預設格式器。而是借助以下項目手動註冊格式器

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

  • org.springframework.format.datetime.DateFormatterRegistrar

例如,以下組態註冊了全域 yyyyMMdd 格式

  • Java

  • Kotlin

  • Xml

@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;
	}
}
@Configuration
class ApplicationConfiguration {

	@Bean
	fun conversionService(): FormattingConversionService {
		// Use the DefaultFormattingConversionService but do not register defaults
		return DefaultFormattingConversionService(false).apply {

			// Ensure @NumberFormat is still supported
			addFormatterForFieldAnnotation(NumberFormatAnnotationFormatterFactory())

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

			// Register date conversion with a specific global format
			val dateRegistrar = DateFormatterRegistrar()
			dateRegistrar.setFormatter(DateFormatter("yyyyMMdd"))
			dateRegistrar.registerFormatters(this)
		}
	}
}
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
	<property name="registerDefaultFormatters" value="false" />
	<property name="formatters">
		<set>
			<bean class="org.springframework.format.number.NumberFormatAnnotationFormatterFactory" />
		</set>
	</property>
	<property name="formatterRegistrars">
		<set>
			<bean class="org.springframework.format.datetime.standard.DateTimeFormatterRegistrar">
				<property name="dateFormatter">
					<bean class="org.springframework.format.datetime.standard.DateTimeFormatterFactoryBean">
						<property name="pattern" value="yyyyMMdd"/>
					</bean>
				</property>
			</bean>
		</set>
	</property>
</bean>

請注意,在網路應用程式中組態日期和時間格式時,還有額外的考量事項。請參閱 WebMVC 轉換和格式化WebFlux 轉換和格式化