如何计算2个日期之间的假期数C#

时间:2018-09-30 05:14:58

标签: c# c#-4.0 datetimepicker

如何计算2天之间数据库中的假期数

我已经计算出商务天数,但是如何减去两天之间的假日数到工作日呢?

假设我有假期表 与 万圣节11-11 CristMass,12-25

日期: 开始日期= 10-25 结束日期= 01-30

answer =业务天数-2个日期之间的假日编号; 在C#中。 这是我的代码:

 public static void GetBusinessDays(DateTime startD, DateTime endD)
        {
            double calcBusinessDays =
                1 + ((endD - startD).TotalDays * 5 -
                (startD.DayOfWeek - endD.DayOfWeek) * 2) / 7;

            if (endD.DayOfWeek == DayOfWeek.Saturday) calcBusinessDays--;
            if (startD.DayOfWeek == DayOfWeek.Sunday) calcBusinessDays--;

            MessageBox.Show(" " + calcBusinessDays);
        } 

通过此链接:Calculate the number of business days between two dates?

按钮:

 private void button1_Click(object sender, EventArgs e)
        {
            GetBusinessDays(Convert.ToDateTime(metroDateTime1.Value.ToString("yyyy-MM-dd")), Convert.ToDateTime(metroDateTime2.Value.ToString("yyyy-MM-dd")));
        }

PS:我是C#的新手

1 个答案:

答案 0 :(得分:0)

while (Start.Date <= End.Date) 
{ 
    if (Start.DayOfWeek == DayOfWeek.Saturday || Start.DayOfWeek == DayOfWeek.Sunday) 
        holidays++; 
    Start = Start.AddDays(1);
}

可以计算假期计数,但是下面的代码效率更高,因为我们已经知道每7天有2个假期,因此不必进行检查,只需检查days % 7(6天最多)的假期就足够了。

int days = (int)(End - Start).TotalDays + 1;
        int holidays = days / 7 * 2;
        int remain = days % 7;
        DateTime dt = End.AddDays(-remain);
        while (dt.Date <= End.Date)
        {
            if (dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday)
                holidays++;
            dt = dt.AddDays(1);
        }
        int year = Start.Year;
        do
        {
            dt = new DateTime(year, 12, 25); //is chritsmass right?
            if (dt >= Start && dt <= End && dt.DayOfWeek!=DayOfWeek.Saturday && dt.DayOfWeek != DayOfWeek.Sunday) holidays++;
            dt = new DateTime(year, 7, 4); // 4th of july
            if (dt >= Start && dt <= End && dt.DayOfWeek!=DayOfWeek.Saturday && dt.DayOfWeek != DayOfWeek.Sunday) holidays++;
            dt = new DateTime(year, 10, 31); // holoween
            if (dt >= Start && dt <= End && dt.DayOfWeek!=DayOfWeek.Saturday && dt.DayOfWeek != DayOfWeek.Sunday) holidays++;
            year++;
        } while (year <= End.Year);
        int bussinessDays = days - holidays;

Live Demo