计算在C#中两个日期之间的工作日数 [英] Calculate the number of weekdays between two dates in C#

查看:339
本文介绍了计算在C#中两个日期之间的工作日数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能获得两个给定日期之间的工作日数不通过日期之间只是迭代和计数平日里?

How can I get the number of weekdays between two given dates without just iterating through the dates between and counting the weekdays?

似乎相当简单,但我似乎无法找到确凿的正确答案,通过以下遵守:

Seems fairly straightforward but I can't seem to find a conclusive correct answer that abides by the following:


  1. 总应该是包容性的,所以GetNumberOfWeekdays(新的DateTime(2009,11,30),新的日期时间(2009,12,4))应该等于5,这是周一到周五。

  2. 应允许飞跃天

  3. 不只是通过所有的日期计算,而平日的迭代。

我已经找到了<一个href=\"http://stackoverflow.com/questions/1617049/calculate-the-number-of-business-days-between-two-dates\">similar与<问题 href=\"http://stackoverflow.com/questions/1617049/calculate-the-number-of-business-days-between-two-dates/1619375#1619375\">answer即接近但不正确

I've found a similar question with an answer that comes close but is not correct

推荐答案

此<一个href=\"http://www.eggheadcafe.com/community/aspnet/2/44982/how-to-calculate-num-of-w.aspx\">link:

    public static int Weekdays(DateTime dtmStart, DateTime dtmEnd)
    {
        // This function includes the start and end date in the count if they fall on a weekday
        int dowStart = ((int)dtmStart.DayOfWeek == 0 ? 7 : (int)dtmStart.DayOfWeek);
        int dowEnd = ((int)dtmEnd.DayOfWeek == 0 ? 7 : (int)dtmEnd.DayOfWeek);
        TimeSpan tSpan = dtmEnd - dtmStart;
        if (dowStart <= dowEnd)
        {
            return (((tSpan.Days / 7) * 5) + Math.Max((Math.Min((dowEnd + 1), 6) - dowStart), 0));
        }
        return (((tSpan.Days / 7) * 5) + Math.Min((dowEnd + 6) - Math.Min(dowStart, 6), 5));
    }


  [1]: http://www.eggheadcafe.com/community/aspnet/2/44982/how-to-calculate-num-of-w.aspx

测试(每个测试返回5):

Tests (each test returns 5):

    int ndays = Weekdays(new DateTime(2009, 11, 30), new DateTime(2009, 12, 4));
    System.Console.WriteLine(ndays);

    // leap year test
    ndays = Weekdays(new DateTime(2000, 2,27), new DateTime(2000, 3, 5));
    System.Console.WriteLine(ndays);

    // non leap year test
    ndays = Weekdays(new DateTime(2007, 2, 25), new DateTime(2007, 3, 4));
    System.Console.WriteLine(ndays);

这篇关于计算在C#中两个日期之间的工作日数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆