本文主要是介绍Spring boot字符串转日期的转换器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Spring boot字符串转日期的转换器
/*** 字符串转日期的转换器*/
@Component
public class CustomDateConverter implements Converter<String, Date> {private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";private static final String shortDateFormat = "yyyy-MM-dd";/*** @param source* @return*/@Overridepublic Date convert(String source) {if (StringUtils.isBlank(source)) {return null;}source = source.trim();try {if (source.contains("-")) {SimpleDateFormat formatter;if (source.contains(":")) {formatter = new SimpleDateFormat(dateFormat);} else {formatter = new SimpleDateFormat(shortDateFormat);}Date dtDate = formatter.parse(source);return dtDate;} else if (source.matches("^\\d+$")) {Long lDate = new Long(source);return new Date(lDate);}} catch (Exception e) {throw new RuntimeException(String.format("parser %s to Date fail", source));}throw new RuntimeException(String.format("parser %s to Date fail", source));}
}
这篇关于Spring boot字符串转日期的转换器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!