gpt4 book ai didi

java - 如何在Spring中注册java.sql.Timestamp的全局格式化程序?

转载 作者:行者123 更新时间:2023-12-02 12:39:03 25 4
gpt4 key购买 nike

我通过 @RestController Servlet 公开以下 Map:

List<Map<String, Object>> results = jdbcTemplate.queryForList(..);

然后,该映射包含一个 java.sql.Timestamp 对象。

问题:如何设置 Springjaxb/jacksonTimestamp 生成的输出格式?我想全局设置它。我不想查看 map 来手动检测和重新格式化值。

以下方法无效:

@Configuration
public class DateConfig extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry) {
super.addFormatters(registry);
registry.addFormatterForFieldType(java.sql.Timestamp.class, new Formatter<Timestamp>() {
@Override
public String print(Timestamp object, Locale locale) {
return "my custom format";
}
});
}
}

格式化程序已注册,但在序列化为 json 期间从未调用!

当前结果始终类似于:2017-07-10T11:06:02.000+0000。但我想在任何地方都获得 2017-07-10 11:06:02

最佳答案

By default, date and time fields that are not annotated with @DateTimeFormat are converted from strings using the DateFormat.SHORT style. If you prefer, you can change this by defining your own global format.

示例如下:

@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 YourTimeStampFormatter());
registrar.registerFormatters(conversionService);

return conversionService;
}
}

参见here

关于java - 如何在Spring中注册java.sql.Timestamp的全局格式化程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45012709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com