c# - 如何计算从今天算起的8个工作日?

标签 c# asp.net

我有一个场景,我想通过从今天的日期减去 8 个工作日来找到日期。假设今天的日期是 04/21/10。现在我想显示日期是 04/09/10。周末应该被排除在外。

例如。 如果今天的日期是 04/21/10

减去周末: 星期六- 04/10/10 ,04/17/10 周日-04/11/10,04/18/10

输出结果为 04/09/10。

我想用 C# 来做。

任何帮助或建议都会有所帮助。

谢谢, 提交

最佳答案

显然有很多的方法可以做到这一点,但也许对生成器有一点乐趣。我使用过扩展方法,但 YMMV。因此,确定您是否需要使您的代码具有文化意识(或根据您的需要需要的任何描述符)等等

public static class DateTimeExtensions
{
    public static IEnumerable<DateTime> Forwards(this DateTime dateTime)
    {
        return dateTime.Forwards(TimeSpan.FromDays(1));
    }

    public static IEnumerable<DateTime> Forwards(this DateTime dateTime, TimeSpan span)
    {
        while (true)
        {
            yield return dateTime += span;
        }
    }

    public static IEnumerable<DateTime> Backwards(this DateTime dateTime)
    {
        return dateTime.Backwards(TimeSpan.FromDays(1));
    }

    public static IEnumerable<DateTime> Backwards(this DateTime dateTime, TimeSpan span)
    {
        return dateTime.Forwards(-span);
    }

    public static bool IsWorkingDay(this DateTime dateTime)
    {
        return dateTime.IsWorkingDay(Thread.CurrentThread.CurrentUICulture);
    }

    public static bool IsWorkingDay(this DateTime dateTime, CultureInfo culture)
    {
        return !dateTime.IsWeekend(culture)
            && !dateTime.IsHoliday(culture);
    }

    public static bool IsWeekend(this DateTime dateTime)
    {
        return dateTime.IsWeekend(Thread.CurrentThread.CurrentUICulture);
    }

    public static bool IsWeekend(this DateTime dateTime, CultureInfo culture)
    {
        // TOOD: Make culturally aware

        return dateTime.DayOfWeek == DayOfWeek.Saturday
            || dateTime.DayOfWeek == DayOfWeek.Sunday;
    }

    public static bool IsHoliday(this DateTime dateTime)
    {
        return dateTime.IsHoliday(Thread.CurrentThread.CurrentUICulture);
    }

    public static bool IsHoliday(this DateTime dateTime, CultureInfo culture)
    {
        throw new NotImplementedException("TODO: Get some culture aware holiday data");
    }
}

然后使用 DateTime 生成器为一些 LINQ 表达式提供动力:

        // Display every holiday from today until the end of the year
        DateTime.Today.Forwards()
            .TakeWhile(date => date.Year <= DateTime.Today.Year)
            .Where(date => date.IsHoliday())
            .ForEach(date => Console.WriteLine(date));

你明白了

关于c# - 如何计算从今天算起的8个工作日?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2681787/

相关文章:

c# - 如何使 CommandBar 打开到屏幕底部?

c# - 更改外键约束命名约定

文件夹 App_Code 中的 C# 访问类

c# - 在维护 session 的同时将网络场迁移到 asp.net 的运行时版本 4

c# - ASP.NET Repeater : Is it possible to display on the first item one element, 但不适用于其余项目?

c# - 别名/缩短 .NET 中的命名空间

c# - 尝试从 Visual Studio 2013 update 4 发布 azure webjob

c# - "Incorrect syntax near ' = '"运行时错误 c# asp.net

asp.net - 如何在 ASP.net 母版页中使用 jQuery AJAX?

c# - C# 中用于视频的文件上传控件