業(yè)務(wù)上需要同時允許輸入多種時間格式1995,1995-01,1995-03-11,這三種形式.以字符串輸入,保證存入數(shù)據(jù)庫需要格式化且保留原始輸入,代碼如下.
使用枚舉固定時間格式
public enum DateEnum {
YYYY_MM_DD("yyyy-MM-dd", "[0-9]{4}-[0-9]{2}-[0-9]{2}", Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}")),
YYYY_MM("yyyy-MM", "[0-9]{4}-[0-9]{2}", Pattern.compile("[0-9]{4}-[0-9]{2}")),
YYYY("yyyy", "[0-9]{4}", Pattern.compile("[0-9]{4}"));
private String format;
//此處正則較為簡單,可以按需求使用更準(zhǔn)確的正則
private String regex;
//Pattern的創(chuàng)建非常消耗性能,所以在此處初始化重復(fù)使用
private Pattern pattern;
DateEnum(String format, String regex, Pattern pattern) {
this.format = format;
this.regex = regex;
this.pattern = pattern;
}
public Pattern getPattern() {
return pattern;
}
public String getFormat() {
return format;
}
public String getRegex() {
return regex;
}
}
編寫格式化工具,使用枚舉
@Setter
@Getter
@ToString
public class DateFormatDTO {
/**
* 時間類型
*/
private String dateType;
/**
* 格式化的時間
*/
private Date date;
/**
* 原始時間字符串格式化,返回格式化時間以及格式化的類型
* @param dateStr 時間原始字符串
* @return
*/
public static DateFormatDTO formatDTO(String dateStr) {
DateFormatDTO dateFormatDTO = new DateFormatDTO();
boolean notHasMatchedDate = true;
DateEnum[] values = DateEnum.values();
for (DateEnum dateEnum : values) {
Pattern pattern = dateEnum.getPattern();
boolean matches = pattern.matcher(dateStr).matches();
if (matches) {
notHasMatchedDate = false;
SimpleDateFormat sdf = new SimpleDateFormat(dateEnum.getFormat());
try {
dateFormatDTO.date = sdf.parse(dateStr);
dateFormatDTO.dateType = dateEnum.getFormat();
} catch (ParseException e) {
//這個異常處理手法只做參考
throw new ApplicationException(new ExceptionContext("日期格式錯誤"), "200005", dateStr);
}
}
}
// 依然為true,說明沒有一種時間格式的正則匹配
if (notHasMatchedDate) {
throw new ApplicationException(new ExceptionContext("日期格式錯誤"), "200005", dateStr);
}
return dateFormatDTO;
}
}
業(yè)務(wù)使用,工具格式化后分別賦值到bean,保存到DB
//格式化生日
//從入?yún)ean取出原始時間
if (StringUtils.isNotBlank(personBasicInfo.getBirthDateStr())) {
DateFormatDTO birthDateFormat = DateFormatDTO.formatDTO(personBasicInfo.getBirthDateStr().trim());
personBasicInfo.setBirthDate(birthDateFormat.getDate());
personBasicInfo.setBirthDateType(birthDateFormat.getDateType());
}
//賦值給入?yún)ean后,可以執(zhí)行保存到DB操作
這么做的意義在于,允許多種時間格式輸入,同時后續(xù)還可以按時間排序.