Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Days to a Date but Excluding Weekends

Tags:

date

c#

f#

Given a date how can I add a number of days to it, but exclude weekends. For example, given 11/12/2008 (Wednesday) and adding five will result in 11/19/2008 (Wednesday) rather than 11/17/2008 (Monday).

I can think of a simple solution like looping through each day to add and checking to see if it is a weekend, but I'd like to see if there is something more elegant. I'd also be interested in any F# solution.

like image 208
Bob Avatar asked Nov 10 '08 21:11

Bob


People also ask

How do you exclude weekends in Excel by date?

Press "Tab." Click inside A3 to display the bold cell border and a tiny square in the lower right corner. Point over this corner to convert the cursor to the "+" symbol. Click and drag down the column to display the dates, excluding weekends.

How do I calculate days between dates in Excel and not including weekends?

If you'd like to calculate the difference between two dates while excluding weekends and holidays, use the NETWORKDAYS function instead. This also looks for 3 arguments: the start date, the end date, and optional holidays. Unlike the WORKDAY function, the NETWORKDAYS function does include or count the start day.

What does exclude weekends mean?

Excluding Weekends and Holidays means movement on Saturday and Sunday is limited to the period of time beginning one-half hour before sunrise and ending at 12:00 Noon, and is prohibited all day on New Year's Day, Memorial Day, Independence Day, Labor Day, Thanksgiving, the day after Thanksgiving, and Christmas.


2 Answers

using Fluent DateTime https://github.com/FluentDateTime/FluentDateTime

var dateTime = DateTime.Now.AddBusinessDays(4); 
like image 62
Simon Avatar answered Oct 02 '22 15:10

Simon


public DateTime AddBusinessDays(DateTime dt, int nDays) {     int weeks = nDays / 5;     nDays %= 5;     while(dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday)         dt = dt.AddDays(1);      while (nDays-- > 0)     {         dt = dt.AddDays(1);         if (dt.DayOfWeek == DayOfWeek.Saturday)             dt = dt.AddDays(2);     }     return dt.AddDays(weeks*7); } 
like image 35
LeppyR64 Avatar answered Oct 02 '22 16:10

LeppyR64