Java计算两个日期的相差天数
计算两个日期相差天数
Java1.8新类LocalDateTime
这次用到的时间类是LocalDateTime,它与Java其他的时间类不同的是,LocalDateTime是不储存时区数据的。因此,LocalDateTime也无法转化成时间戳格式。
计算相差天数
因为本文的计算天数,不考虑时分秒带来的影响。因此,我们不需要用LocalDateTime精度这么高的时间类,我们只需要用LocalDate即可。
LocalDateTime转成LocalDate的方法也很简单,代码如下:
LocalDateTime startTime = LocalDateTime.now();
LocalDate start = startDate.toLocalDate();
如果大家去百度的话,会发现很多的博客都会告诉大家用Period这个类的between()方法来计算相差的天数。但是这个方法只能用于同一个月内的天数相减。
但是通过查看LocalDate的源码,发现了另外一种计算相差天数的方法。LocalDate中有一个方法叫做toEpochDay(),它是将LocalDate中的时间,转换成距离1970年1月1日的天数,源码如下:
@Override
public long toEpochDay() {
long y = year;
long m = month;
long total = 0;
total += 365 * y;
if (y >= 0) {
total += (y + 3) / 4 - (y + 99) / 100 + (y + 399) / 400;
} else {
total -= y / -4 - y / -100 + y / -400;
}
total += ((367 * m - 362) / 12);
total += day - 1;
if (m > 2) {
total--;
if (isLeapYear() == false) {
total--;
}
}
return total - DAYS_0000_TO_1970;
}
以后也可以用这个方法去计算其他与日期相关的问题,可以说这个方法也非常的巧妙。
因此,我们只需要将结束日期的LocalDate调用这个函数减去开始日期的值即可:
public long diffFromDate(LocalDateTime startDate, LocalDateTime endDate){
LocalDate start = startDate.toLocalDate();
LocalDate end = endDate.toLocalDate();
long res = end.toEpochDay()-start.toEpochDay();
return res;
}
计算两个日期相差天数(除去双休日)
首先可以将问题简化一下,可以知道,不论开始、结束日期,只要经过7天,必定就有两天是周末。因此问题可以简化为,一周内的双休日天数+周数*2.
public int checkWeekendDay(int startDate, int endDate, int days){
int weekEndCount = 0;
if (days<1){
if (startDate==6 || startDate==0){
weekEndCount+=1;
}
} else {
weekEndCount+=(days/7)*2;
weekEndCount+=calculateWeekendDays(startDate,endDate);
}
return weekEndCount;
}
public int calculateWeekendDays(int startDate, int endDate){
int weekendCount=0;
if (startDate==0&&endDate==6) {
weekendCount += 2;
}else if (startDate<endDate&&endDate==6){
weekendCount+=1;
}else if (startDate<endDate&&startDate==0){
weekendCount+=1;
}else if (startDate>endDate){
weekendCount+=2;
}
if (startDate==endDate){
if (startDate==6||endDate==0){
weekendCount+=1;
}
}
return weekendCount;
}