多种时间格式化处理
2018-11-29 本文已影响0人
从入门到脱发
业务上需要同时允许输入多种时间格式1995,1995-01,1995-03-11,这三种形式.以字符串输入,保证存入数据库需要格式化且保留原始输入,代码如下.
使用枚举固定时间格式
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;
//此处正则较为简单,可以按需求使用更准确的正则
private String regex;
//Pattern的创建非常消耗性能,所以在此处初始化重复使用
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;
}
}
业务使用,工具格式化后分别赋值到bean,保存到DB
//格式化生日
//从入参bean取出原始时间
if (StringUtils.isNotBlank(personBasicInfo.getBirthDateStr())) {
DateFormatDTO birthDateFormat = DateFormatDTO.formatDTO(personBasicInfo.getBirthDateStr().trim());
personBasicInfo.setBirthDate(birthDateFormat.getDate());
personBasicInfo.setBirthDateType(birthDateFormat.getDateType());
}
//赋值给入参bean后,可以执行保存到DB操作
这么做的意义在于,允许多种时间格式输入,同时后续还可以按时间排序.