首页 > 解决方案 > 如何计算工作 15 天并获得结束日期?

问题描述

用户入住酒店时如何计算我的实际工作日?我只想计算除周六和周日以外的工作日。请检查以下函数的计数工作日,但在参数中我输入了开始日期和结束日期。我只想发送开始日期,它会自动计算 15 个工作日并返回给我结束日期。//天数

public static double 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--;

    return calcBusinessDays;
} 

我想要这样:

public static Datetime GetBusinessDays(DateTime startDate)
{
    Datetime After15WorkingDaysDate;
    return After15WorkingDaysDate;
}

标签: c#asp.net

解决方案


这里有两种方法。

这个想法是生成范围内的每个日期,确定它是否是工作日,然后才将其添加到结果列表中。

GetBusinessDaysInRange返回给定开始日期和结束日期之间的工作日日期列表。结束日期是唯一的,即如果结束日期是工作日,则它不会成为结果的一部分。

// Returns a list of the dates of the Business Days between the given start and end date
public static IEnumerable<DateTime> GetBusinessDaysInRange(DateTime startDate, DateTime endDate, DayOfWeek[] closedOn) {

   if (endDate < startDate) {
        throw new ArgumentException("endDate must be before startDate");    
   }

    var businessDays = new List<DateTime>();
    var date = startDate;

    while (date < endDate) {
        if (!closedOn.Contains(date.DayOfWeek)) {
            businessDays.Add(date);
        }
        date = date.AddDays(1);
    }

    return businessDays;
}

GetFixedNumberOfBusinessDays从给定的天数(您要求的方法)返回从给定开始的工作日的日期列表。

// Returns a list of the dates of the Business Days from the given start with the given number of days
public static IEnumerable<DateTime> GetFixedNumberOfBusinessDays(DateTime startDate, int numberOfBusinessDays, DayOfWeek[] closedOn) {

    if (numberOfBusinessDays < 0) {
        throw new ArgumentException("numberOfBusinessDays must be zero or positive.");  
    }

    var businessDays = new List<DateTime>();
    var date = startDate;

    while (businessDays.Count() < numberOfBusinessDays) {
        if (!closedOn.Contains(date.DayOfWeek)) {
            businessDays.Add(date);
        }
        date = date.AddDays(1);
    }

    return businessDays;
}

引入该参数DayOfWeek[] closedOn是因为您不想硬编码不是工作日的星期几。

返回类型已更改为,IEnumerable<DateTime>因此此方法更通用。如果您只想要天数并且对实际日期不感兴趣,只需.Count()在结果上运行 a。如果您想要结束日期,请致电.Last()

.Net Fiddle使用示例:

var closedOn = new DayOfWeek[] { DayOfWeek.Saturday, DayOfWeek.Sunday };
var start = new DateTime(2018, 07, 23);
var numberOfDays = 10;

var businessDays = GetFixedNumberOfBusinessDays(end, numberOfDays, closedOn);

int actualNumberOfBusinessDays = businessDays.Count(); // 10    
DateTime endDate = businessDays.Last();                // Friday, August 3, 2018

推荐阅读