Java对输入的日期进行校验
在大多数时候,前端通过组件传递到后端的时间是没问题的,在excel导入的时候,时间字符串需要进行验证。
下面的代码实现了对时间字符串的校验:
package com.bflc.utils.uuid;
import com.bflc.utils.StringUtils;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Test {
//各个月中最大天数
private static int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
/**
* 判断日期合法性
* @param year 年
* @param month 月
* @param day 日
* @return
*/
public static boolean judgeDateCorrect(int year, int month, int day) {
//首先判断月份是否合法
if (month >= 1 && month <= 12) {
//判断是否为闰年
if ((year % 100 == 0 && year % 400 == 0) || year % 4 == 0) {
//判断当前月份是否为2月,因为闰年的2月份为29天
if (month == 2 && day <= 29) {
return true;
} else {
if (day <= days[month - 1]) {
return true;
}
}
} else {
if (day <= days[month - 1]) {
return true;
}
}
}
return false;
}
/**
* 根据字符串获取年月日
* @param dateS 日期字符串
* @param format 格式化模板
* @return
*/
public static List<Integer> getDateYMD(String dateS, String format) {
if (StringUtils.isEmpty(dateS)) {
return new ArrayList<>();
}
try {
Date date = new SimpleDateFormat(format).parse(dateS)
String[] split = dateS.split("-");
if (split.length != 3) {
return new ArrayList<>();
}
List<Integer> res = new ArrayList<>();
res.add(Integer.parseInt(split[0]));
res.add(Integer.parseInt(split[1]));
res.add(Integer.parseInt(split[2]));
return res;
} catch (Exception e) {
return new ArrayList<>();
}
}
public static void main(String[] args) {
List<Integer> dateYMD = getDateYMD("2022-02-15", "yyyy-MM-dd");
for (int i = 0; i < dateYMD.size(); i++) {
System.out.println(dateYMD.get(i));
}
boolean b = judgeDateCorrect(dateYMD.get(0), dateYMD.get(1), dateYMD.get(2));
System.out.println(b);
}
}
文章评论