gpt4 book ai didi

java - 如何获得给定日期范围内的天数?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:59:09 26 4
gpt4 key购买 nike

我尝试使用以下方法查找天数,

public static int findNoOfDays(int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, day);
int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
return days;
}

同样,我想通过给出开始日期和结束日期来获取天数,并获取不包括周六和周日的天数。

最佳答案

这里有一个计算两个日期之间的天数的方法:

private int calculateNumberOfDaysBetween(Date startDate, Date endDate) {
if (startDate.after(endDate)) {
throw new IllegalArgumentException("End date should be grater or equals to start date");
}

long startDateTime = startDate.getTime();
long endDateTime = endDate.getTime();
long milPerDay = 1000*60*60*24;

int numOfDays = (int) ((endDateTime - startDateTime) / milPerDay); // calculate vacation duration in days

return ( numOfDays + 1); // add one day to include start date in interval
}

下面是一个计算指定时间段内周末天数的方法:

private static int calculateNumberOfWeekendsInRange(Date startDate, Date endDate) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);

int counter = 0;
while(!calendar.getTime().after(endDate)) {
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek==1 || dayOfWeek==7) {
counter++;
}
calendar.add(Calendar.DAY_OF_MONTH, 1);
}

return counter;
}

编辑:

我更改了上一个方法,现在它计算排除周末的天数:

private int calculateNumberOfDaysExcludeWeekends(Date startDate, Date endDate) {
if (startDate.after(endDate)) {
throw new IllegalArgumentException("End date should be grater or equals to start date");
}

Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);

int numOfDays = 0;
while(!calendar.getTime().after(endDate)) {
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if ( (dayOfWeek>1) && (dayOfWeek<7) ) {
numOfDays++;
}
calendar.add(Calendar.DAY_OF_MONTH, 1);
}

return numOfDays;
}

关于java - 如何获得给定日期范围内的天数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11794604/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com