解決springboot 實體類String轉Date類型的坑
更新時間:2021年10月25日 10:32:40 作者:DemonsPan
這篇文章主要介紹了解決springboot 實體類String轉Date類型的坑,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
springboot 實體類String轉Date類型
前端傳入一個String的時間字符串如:2019-07-18 23:59:59
后端實體類要在頭頂加注解:
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")

不然會出現(xiàn)報錯

Date解析String類型的參數(shù)
1.首先建立String to Date 的解析實現(xiàn)
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateConverter implements Converter<String, Date> {
private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
private static final String shortDateFormat = "yyyy-MM-dd";
@Override
public Date convert(String value) {
if (StringUtils.isEmpty(value)) {
return null;
}
value = value.trim();
try {
if (value.contains("-")) {
SimpleDateFormat formatter;
if (value.contains(":")) {
formatter = new SimpleDateFormat(dateFormat);
} else {
formatter = new SimpleDateFormat(shortDateFormat);
}
Date dtDate = formatter.parse(value);
return dtDate;
} else if (value.matches("^\\d+$")) {
Long lDate = new Long(value);
return new Date(lDate);
}
} catch (Exception e) {
throw new RuntimeException(String.format("parser %s to Date failed", value));
}
throw new RuntimeException(String.format("parser %s to Date failed", value));
}
}
2.創(chuàng)建全局的解析配置
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import javax.annotation.PostConstruct;
@Configuration
public class DateHandlerAdapter {
@Autowired
private RequestMappingHandlerAdapter handlerAdapter;
/**
* 增加字符串轉日期的全局適配器
*/
@PostConstruct
public void initEditableAvlidation() {
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter
.getWebBindingInitializer();
if (initializer.getConversionService() != null) {
GenericConversionService genericConversionService = (GenericConversionService) initializer
.getConversionService();
genericConversionService.addConverter(new StringToDateConverter());
}
}
}
添加完這兩個文件以后 在傳參數(shù)類型為Date的參數(shù)時就不會再報 date解析失敗的錯誤了。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring Boot中捕獲異常錯誤信息并將其保存到數(shù)據(jù)庫中的操作方法
這篇文章主要介紹了Spring Boot中捕獲異常錯誤信息并將其保存到數(shù)據(jù)庫中的操作方法,通過實例代碼介紹了使用Spring Data JPA創(chuàng)建一個異常信息的存儲庫接口,以便將異常信息保存到數(shù)據(jù)庫,需要的朋友可以參考下2023-10-10
Java?HashMap中除了死循環(huán)之外的那些問題
這篇文章主要介紹了Java?HashMap中除了死循環(huán)之外的那些問題,這些問題大致可以分為兩類,程序問題和業(yè)務問題,下面文章我們一個一個來看,需要的小伙伴可以參考一下2022-05-05
Spring @Configuration和@Component的區(qū)別
今天小編就為大家分享一篇關于Spring @Configuration和@Component的區(qū)別,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12

