c#DateTime添加/减less工作日

我有一个场景,给定date( DateTime ),该date加/减x天(通过DateTime.AddDays实现)必须加上或减去x工作日,即跳过周末和假日。 我怎样才能做到这一点? 我应该实现我自己的版本,并将其附加到日历或东西?

我build议你必须自己实现它,然后在这样的扩展方法里面实现:

public static class DateTimeExtensions { public static DateTime AddWorkdays(this DateTime originalDate, int workDays) { DateTime tmpDate = originalDate; while (workDays > 0) { tmpDate = tmpDate.AddDays(1); if (tmpDate.DayOfWeek < DayOfWeek.Saturday && tmpDate.DayOfWeek > DayOfWeek.Sunday && !tmpDate.IsHoliday()) workDays--; } return tmpDate; } public static bool IsHoliday(this DateTime originalDate) { // INSERT YOUR HOlIDAY-CODE HERE! return false; } }
public static class DateTimeExtensions { public static DateTime AddWorkdays(this DateTime originalDate, int workDays) { DateTime tmpDate = originalDate; while (workDays > 0) { tmpDate = tmpDate.AddDays(1); if (tmpDate.DayOfWeek < DayOfWeek.Saturday && tmpDate.DayOfWeek > DayOfWeek.Sunday && !tmpDate.IsHoliday()) workDays--; } return tmpDate; } public static bool IsHoliday(this DateTime originalDate) { // INSERT YOUR HOlIDAY-CODE HERE! return false; } } 

基于塔兹的 链接 :

 public static class DateTimeExtensions { public static DateTime AddWorkDays(this DateTime date, int workingDays) { int direction = workingDays < 0 ? -1 : 1; DateTime newDate = date; while (workingDays != 0) { newDate = newDate.AddDays(direction); if (newDate.DayOfWeek != DayOfWeek.Saturday && newDate.DayOfWeek != DayOfWeek.Sunday && !newDate.IsHoliday()) { workingDays -= direction; } } return newDate; } public static bool IsHoliday(this DateTime date) { // You'd load/cache from a DB or file somewhere rather than hardcode DateTime[] holidays = new DateTime[] { new DateTime(2010,12,27), new DateTime(2010,12,28), new DateTime(2011,01,03), new DateTime(2011,01,12), new DateTime(2011,01,13) }; return holidays.Contains(date.Date); } } 

我最近做了这个:

 private DateTime CalculateFutureDate(DateTime fromDate, int numberofWorkDays, ICollection<DateTime> holidays) { var futureDate = fromDate; var daterange = Enumerable.Range(1, numberofWorkDays * 2); var dateSet = daterange.Select (d => futureDate.AddDays(d)); var dateSetElim = dateSet.Except(holidays).Except(dateSet.Where( s =>s.DayOfWeek == DayOfWeek.Sunday).Except(dateSet.Where (s=>s.DayOfWeek==DayOfWeek.Saturday) )); //zero-based array futureDate = dateSetElim.ElementAt(numberofWorkDays-1); return futureDate; } 

你需要检查一下行为,我只添加他们!

我花了一些时间来解决这个问题……我已经创build了一个数据库表,我把这个数据库放在了一个数组中。 所有信贷Kev(在这个职位) ..我不得不修改他的工作是为了我。

就我而言,如果第一天是星期六,而我的工作天数= -1,我想星期四回来(因为我的约会不能在周末或假期中……这一定是一个工作日..在这个星期五。)

Kev的代码可以传回星期天…下面的代码将把它带到前一个工作日(通常是一个星期五 – 除非星期五是假期,星期四会传回去)。

 public static DateTime AddWorkDays(this DateTime date, int workingDays, params Holidays[] bankHolidays) { int direction = workingDays < 0 ? -1 : 1; DateTime newDate = date; // If a working day count of Zero is passed, return the date passed if (workingDays == 0) { newDate = date; } else { while (workingDays != -direction) { if (newDate.DayOfWeek != DayOfWeek.Saturday && newDate.DayOfWeek != DayOfWeek.Sunday && Array.IndexOf(bankHolidays, newDate) < 0) { workingDays -= direction; } // if the original return date falls on a weekend or holiday, this will take it to the previous / next workday, but the "if" statement keeps it from going a day too far. if (workingDays != -direction) { newDate = newDate.AddDays(direction); } } } return newDate; } 

这是我简单的Holidays类:

 using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Clarity.Utilities { public class Holidays { public int Id { get; set; } public DateTime dtHoliday { get; set; } public string Desc { get; set; } public bool Active { get; set; } } } 

以下是如何填充数组:

 private Holidays[] PopulateArrayWithDates() { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConn"].ConnectionString); DateTime[] dtHolidays = new DateTime[] { }; string sql = @"SELECT HolDate, HolName FROM [Server].DBName.dbo.tblHolidays"; SqlCommand ADDCmd = new SqlCommand(sql, con); DataTable table = new DataTable(); DataTable tbl = new DataTable(); Utilities.Holidays[] allRecords = null; using (var command = new SqlCommand(sql, con)) { con.Open(); using (var reader = command.ExecuteReader()) { var list = new List<Holidays>(); while (reader.Read()) list.Add(new Holidays { dtHoliday = reader.GetDateTime(0), Desc = reader.GetString(1) }); allRecords = list.ToArray(); } } return allRecords; } 

我正在寻找添加和减去周末跳过的date,这是谷歌的第一个条目。 我不喜欢这里的任何答案,所以我会添加一个我自己以防万一有人像我一样在这里结束:

 public static DateTime AddExcludingWeekends(this DateTime dateTime, int nDays) { var wholeWeeks = nDays / 5; //since nDays does not include weekdays every week is considered as 5 days var absDays = Math.Abs(nDays); var remaining = absDays % 5; //results in the number remaining days to add or substract excluding the whole weeks var direction = nDays / absDays;//results in 1 if nDays is posisive or -1 if it's negative while (dateTime.DayOfWeek == DayOfWeek.Saturday || dateTime.DayOfWeek == DayOfWeek.Sunday) dateTime = dateTime.AddDays(direction); //If we are already in a weekend, get out of it while (remaining-- > 0) {//add remaining days... dateTime = dateTime.AddDays(direction); if (dateTime.DayOfWeek == DayOfWeek.Saturday) dateTime = dateTime.AddDays(direction * 2);//...skipping weekends } return dateTime.AddDays(wholeWeeks * 7); //Finally add the whole weeks as 7 days, thus skipping the weekends without checking for DayOfWeek } 

我希望这有助于某人。

你应该检查一天是否自己工作,因为DateTime类不能知道哪一天将是今年的假期:)

你可能应该有一个数据库节假日检查,如果日加号/减号的值等于数据库中的一个值加/减另一个,因为不是每个人都有相同的假期。

我已经修改了以前对更多function方法的回答。 我在下面提供了两个解决scheme,一个使用IEnumerable,一个使用IObservable和Reactive Extensions

使用IObservable

 public static class DateTimeExtensions { public static DateTime AddWorkDays(this DateTime date, int workingDays) { return Observable .Generate (date, arg => true, arg => arg.AddDays(workingDays < 0 ? -1 : 1), arg => arg) .Where(newDate => (newDate.DayOfWeek != DayOfWeek.Saturday && newDate.DayOfWeek != DayOfWeek.Sunday && !newDate.IsHoliday())) .Take(Math.Abs(workingDays) + 1) .LastAsync() .Wait(); } public static bool IsHoliday(this DateTime date) { return false; } } 

使用IEnumerable

 public static class DateTimeExtensions { public static DateTime AddWorkDays(this DateTime date, int workingDays) { return date.GetDates(workingDays < 0) .Where(newDate => (newDate.DayOfWeek != DayOfWeek.Saturday && newDate.DayOfWeek != DayOfWeek.Sunday && !newDate.IsHoliday())) .Take(Math.Abs(workingDays)) .Last(); } private static IEnumerable<DateTime> GetDates(this DateTime date, bool isForward) { while (true) { date = date.AddDays(isForward ? -1 : 1); yield return date; } } public static bool IsHoliday(this DateTime date) { return false; } } 

简单的解决scheme是在这里试试看,享受编码

 public class Program { public static void Main(string[] args) { Double days= 7; string s=DateTime.Now.AddDays(7).ToString("dd/MM/yyyy"); DateTime dt= OrderDeliveryDate(days); Console.WriteLine("dt"+dt.ToString("dd/MM/yyyy")); } public static DateTime OrderDeliveryDate(Double days) { Double count=0; for(int i=0;i<days;i++) { if(DateTime.Now.AddDays(i).DayOfWeek.ToString() == "Saturday") { count= count+1; } else if(DateTime.Now.AddDays(i).DayOfWeek.ToString() == "Sunday") { count=count+1; } } days=days+count; return DateTime.Now.AddDays(days); } }