在日期存储和操作时,很多格式问题导致的异常十分令人头疼,以下是我在使用操作日期之前进行的常用校验,分为两种:
一、正则校验
代码:
// 判断日期格式是否满足指定日期格式 yyyy-MM-dd HH:mm
if (checkDate.matches("(\\d{4}-\\d{2}-\\d{2})\\s+(\\d{2}:\\d{2})"))
{
// 满足则进行转换(此处满足的是异常格式),转换成正常格式
SimpleDateFormat old_sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat new_sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date parse = old_sdf.parse(checkDate);
checkDate = new_sdf.format(parse);
} catch (Exception e) {
logger.error("时间格式转换异常!", e);
}
}
二、使用格式转换校验
代码:
public void test(checkDate) {
if (isValidDate(checkDate, "yyyy-MM-dd HH:mm")) {
checkDate = transferDataFormat(checkDate, "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH:mm:ss");
}
}
public static boolean isValidDate(String date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(false);
try {
sdf.parse(date);
return true;
} catch (Exception e) {
return false;
}
}
public static String transferDataFormat(String date, String old_format, String new_format) {
SimpleDateFormat old_sdf = new SimpleDateFormat(old_format);
try {
Date parse = old_sdf.parse(date);
SimpleDateFormat new_sdf = new SimpleDateFormat(new_format);
return new_sdf.format(parse);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
2051

被折叠的 条评论
为什么被折叠?



