本文小編為大家詳細介紹“Spring Boot日期時間如何處理”,內容詳細,步驟清晰,細節處理妥當,希望這篇“Spring Boot日期時間如何處理”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
這種情況要和時間作為Json字符串時區別對待,因為前端json轉后端pojo底層使用的是Json序列化Jackson工具(HttpMessgeConverter);而時間字符串作為普通請求參數傳入時,轉換用的是Converter,兩者在處理方式上是有區別。
實現 org.springframework.core.convert.converter.Converter,自定義參數轉換器,如下:
@Configuration
public class DateConverterConfig {
@Bean
public Converter<String, LocalDate> localDateConverter() {
return new Converter<String, LocalDate>() {
@Override
public LocalDate convert(String source) {
return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
};
}
@Bean
public Converter<String, LocalDateTime> localDateTimeConverter() {
return new Converter<String, LocalDateTime>() {
@Override
public LocalDateTime convert(String source) {
return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
};
}
}點評:以上兩個bean會注入到spring mvc的參數解析器(好像叫做ParameterConversionService),當傳入的字符串要轉為LocalDateTime類時,spring會調用該Converter對這個入參進行轉換。
注意:關于自定義的參數轉換器 Converter,這有個坑,若將上面匿名內部類的寫法精簡成lambda表達式的方式:
@Bean
@ConditionalOnBean(name = "requestMappingHandlerAdapter")
public Converter<String, LocalDate> localDateConverter() {
return source -> LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
}當再次啟動項目時會出現異常:
Caused by: java.lang.IllegalArgumentException: Unable to determine source type <S> and target type <T> for your Converter [com.example.demo126.config.MappingConverterAdapter$$Lambda$522/817994751]; does the class parameterize those types?
是由于:
web項目啟動注冊requestMappingHandlerAdapter的時候會初始化WebBindingInitializer
adapter.setWebBindingInitializer(getConfigurableWebBindingInitializer());
而ConfigurableWebBindingInitializer需要FormattingConversionService, 而FormattingConversionService會將所有的Converter添加進來,添加的時候需要獲取泛型信息:
@Override
public void addFormatters(FormatterRegistry registry) {
for (Converter<?, ?> converter : getBeansOfType(Converter.class)) {
registry.addConverter(converter);
}
for (GenericConverter converter : getBeansOfType(GenericConverter.class)) {
registry.addConverter(converter);
}
for (Formatter<?> formatter : getBeansOfType(Formatter.class)) {
registry.addFormatter(formatter);
}
}添加Converter.class 一般是通過接口獲取兩個泛型的具體類型
public ResolvableType as(Class<?> type) {
if (this == NONE) {
return NONE;
}
Class<?> resolved = resolve();
if (resolved == null || resolved == type) {
return this;
}
for (ResolvableType interfaceType : getInterfaces()) {
ResolvableType interfaceAsType = interfaceType.as(type);
if (interfaceAsType != NONE) {
return interfaceAsType;
}
}
return getSuperType().as(type);
}Lambda表達式的接口是Converter,并不能得到具體的類型,既然如此,那解決辦法:
最簡單的方法就是不適用Lambda表達式,還使用匿名內部類,這樣就不會存在上述問題
就是等requestMappingHandlerAdapterbean注冊完成之后再添加自己的converter就不會注冊到FormattingConversionService中
@Bean
@ConditionalOnBean(name = "requestMappingHandlerAdapter")
public Converter<String, LocalDateTime> localDateTimeConverter() {
return source -> LocalDateTime.parse(source, DateTimeUtils.DEFAULT_FORMATTER);
}還可以對前端傳遞的string進行正則匹配,如yyyy-MM-dd HH:mm:ss、yyyy-MM-dd、 HH:mm:ss等,進行匹配。以適應多種場景。
@Component
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String value) {
/**
* 可對value進行正則匹配,支持日期、時間等多種類型轉換
* 這里在匹配Date日期格式時直接使用了 hutool 為我們已經寫好的解析工具類,這里就不重復造輪子了
* cn.hutool.core.date.DateUtil
* @param value
* @return
*/
return DateUtil.parse(value.trim());
}
}注:這里在匹配Date日期格式時直接使用了 hutool 為我們已經寫好的解析工具類,這里就不重復造輪子了,下面的方法同樣使用了該工具類,想要在自己的項目中使用該工具類也很簡單,在項目pom文件中引入hutool的依賴就可以了,如下:
<!--hu tool 工具類--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.1.3</version> </dependency>
使用spring自帶注解@DateTimeFormat(pattern = "yyyy-MM-dd"),如下:
@DateTimeFormat(pattern = "yyyy-MM-dd") private Date startDate;
如果使用了自定義參數轉化器,Spring會優先使用該方式進行處理,即Spring注解不生效。
@ControllerAdvice
public class GlobalExceptionHandler {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}
});
binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
});
binder.registerCustomEditor(LocalTime.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalTime.parse(text, DateTimeFormatter.ofPattern("HH:mm:ss")));
}
});
}
}從名字就可以看出來,這是在controller做環切(這里面還可以全局異常捕獲),在參數進入handler之前進行轉換;轉換為我們相應的對象。
請求類型為:post,content-type=application/json, 后臺用@RequestBody接收,默認接收及返回值格式為: yyyy-MM-dd HH:mm:ss
在application.propertities文件中增加如下內容:
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
支持(content-type=application/json)請求中格式為 yyyy-MM-dd HH:mm:ss的字符串,后臺用@RequestBody接收,及返回值date轉為yyyy-MM-dd HH:mm:ss格式string;
不支持(content-type=application/json)請求中yyyy-MM-dd等類型的字符串轉為date; 不支持java8日期api;
@Configuration
public class JacksonConfig {
/** 默認日期時間格式 */
public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/** 默認日期格式 */
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
/** 默認時間格式 */
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
// 忽略json字符串中不識別的屬性
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 忽略無法轉換的對象
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// PrettyPrinter 格式化輸出
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
// NULL不參與序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 指定時區
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
// 日期類型字符串處理
objectMapper.setDateFormat(new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT));
// java8日期日期處理
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
objectMapper.registerModule(javaTimeModule);
converter.setObjectMapper(objectMapper);
return converter;
}
}讀到這里,這篇“Spring Boot日期時間如何處理”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。