本文介绍了如何获取给定日期范围内的天数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

I try to find number of days using following method,

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;
    }

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

likewise I want to get the number of days by giving start date and end date and get the number of days excluding Saturday and Sunday.

推荐答案

是一种计算两个日期之间天数的方法:

Here is a method that calculates the number of days between two dates:

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
}

这里是一种方法它计算指定时间段内的周日数:

And here is a method that calculates the number of weekent days in the specified time period:

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;
}

编辑:

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

I changed last method, now it calculates the number of days exclude weekend days:

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;
}

这篇关于如何获取给定日期范围内的天数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:15