【问题标题】:how to exclude Saturday and Sunday from startDate and endDate datetime objects如何从 startDate 和 endDate 日期时间对象中排除周六和周日
【发布时间】:2018-02-02 12:29:13
【问题描述】:

用 c# 开发。我有两个 DateTime 对象。我必须从天数中消除周六和周日。假设我有 5 天,包括周六和周日。我想检查周六周日的天数并减少天数。

 DateTime startDate = DateTime.ParseExact(startDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
 DateTime endDate = DateTime.ParseExact(endDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
 TimeSpan diff = endDate - startDate;
 days = diff.Days;

我试过了,

How can I calculate the Number of Weekends between two dates

但我无法消除周六周日,因为给定的链接只有在日期差异大于 7 时才会消除周末。还没有我的解决方案。

【问题讨论】:

标签: c# datetime


【解决方案1】:

在两个日期的日期之间进行一个简单的循环并使用DayOfWeek 来检查这一天是星期六还是星期日?

类似下面的东西应该可以工作:

int weekendDays = 0;

for(DateTime date = startDate; date.Date <= endDate.Date; date = date.AddDays(1))
{
    if ((date.DayOfWeek == DayOfWeek.Saturday) || (date.DayOfWeek == DayOfWeek.Sunday))
    {
        weekendDays++;
    }
}

【讨论】:

  • 美丽声明@Adriani
  • @BrunoMiquelin 提议 this edit 但我很确定他的更改不会产生正确的结果。
【解决方案2】:

你冷使用以下:

int daycount = 0;
while (startDate < endDate) 
{
    startDate = startDate.AddDays(1);
    int DayNumInWeek = (int)startDate.DayOfWeek;
    if (DayNumInWeek != 0 && DayNumInWeek != 6)
         daycount += 1;       
}

查看This linkThis link 了解更多信息和选项。

也是 Calculate the number of business days between two dates? 的副本,它有一个很好的 Alpha 的 LINQ 方法

为了获得更好的性能和可读性,您可以实现that

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    相关资源
    最近更新 更多