判断两个日期的跨度是否超过一年
写这个工具类是因为在处理查询业务的时候遇到了一个问题,
要求是查询的时间范围不能超过十二个月,自己找了一下没有比较简单的实现方法,
就自己理了一下思路自己写了这个工具类。
第一代产品
【思路】
把 字符串 类型的日期 转换 为 Date 类型
再由 Date 类型 转换 为 long 类型的毫秒值(这是Date记录时间的本质)
计算出一年的毫秒数,用两个参数时间相减的差进行比较
如果总天数大于 365 天 或者 第二个参数早于第一个参数,则提示不合理输入
import ;
import ;
import ;
/**
* @author 二师兄
* @version V1.0
* @Title: 时间校验工具类
* @Description:
* @date 2020/12/30 10:57
*/
public class DateFomart {
public static void main(String[] args) {
//规定需要转换的日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//文本转日期
try {
Date due = ("2019-02-26");
Date begin = ("2018-02-26");
long time1 = ();
long time2 = ();
long time = time1 - time2;
(time + "=" + time1 + "-" + time2);
if(time > 31536000000L || time < 0){
// throw new BillException("查询时间期间不允许超过12个月。");
// ("查询时间期间不允许超过12个月。");
("查询时间期间不合法");
}
} catch (ParseException e) {
();
}
}
}
但是由于闰年的存在我们需要进行进一步判断,
如果存在跨越闰年 2 月 29 日,那么这一年就是 366 天,
而不能单纯的按照 365 天来计算了。
第二代产品
【思路】
相邻的两个年份最多会出现一个闰年
开始时间是闰年且月份小于2,则在原来的毫秒值上加 1 天(一天是 86400000 毫秒)
或者结束时间是闰年且月份大于2,则加 1 天的毫秒值
以上两条是判断是否存在闰年,是否跨过闰年的 2 月份
最开始的思路不是这样的(写着写着发现这样写代码最少)
import ;
import ;
/**
* @author 二师兄
* @version V1.0
* @Title: 时间校验工具类
* @Description:
* @date 2020/12/30 11:42
*/
public class DateCheckUtil {
/**
* 校验日期区间时间跨度是否在一年之内
* 参数日期格式应为 yyyy-MM-dd,例如:2020-12-31
* @param beginDate 开始日期
* @param dueDate 结束日期
*/
public static boolean checkIsOneYear(String beginDate, String dueDate){
//365天的毫秒数
long ms = 31536000000L;
try {
//规定需要转换的日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//文本转日期
Date due = (dueDate);
Date begin = (beginDate);
long time = () - ();
(time + "=" + () + "-" + ());
//天数大于366天或者小于一天一定属于不合理输入,返回false
if(time > 31622400000L || time < 0L){
// ("查询时间期间不合法。");
return false;
}
//对字符串截取,取出年份和月份
Integer beginYear = ((0, 4));
Integer beginMonth = ((5, 7));
Integer dueYear = ((0, 4));
Integer dueMonth = ((5, 7));
//判断是否为闰年,并跨过2月,如果是则增加一天的毫秒数
if(isLeapYear(beginYear) && beginMonth <= 2){
ms += 86400000;
}else if(isLeapYear(dueYear) && dueMonth >= 2){
ms += 86400000;
}
return time <= ms;
} catch (Exception e) {
();
}
return false;
}
/**
* 给定一个年份,判断是否为闰年
* @param year
* @return
*/
public static boolean isLeapYear(Integer year){
if(year % 100 == 0){
if(year % 400 == 0){
return true;
}
}else if(year % 4 == 0){
return true;
}
return false;
}
public static void main(String[] args) {
String begin = "2020-01-15";
String dueDate = "2021-01-15";
boolean b = checkIsOneYear(begin, dueDate);
(b);
}
}