How can I calculate the Number of Weekends between two dates[Answered] RSS

27 replies

Last post Sep 20, 2010 02:33 AM by robert.westerlund

• mikener

Member

63 Points

230 Posts

How can I calculate the Number of Weekends between two dates

I need to be able to figure out the number of Saturdays and the number of Sundays between two dates.  I know that I can do this by looping through the series of dates between the start date and end date.  Years ago I saw a piece of code that an ex-co worker wrote that accomplished this task using a formula.  The formula was extemely effecient.  Unfortunately I no longer have access to this code.  Does anyone have an algorithm that will perform this calculation that I can make use of?

Thanks

• robert.weste...

Participant

1630 Points

368 Posts

Re: How can I calculate the Number of Weekends between two dates

I don't have a formula for the calculation, but couldn't you just determine which day is the start date (from a datetime, that is not hard at all) and calculate how many days there are from the start date to the end date (should also be an easy calculation to make). Since you know that there is one saturday and one sunday each seven days, you could calculate how many full weeks there are between the two dates. Then you could either use the rest from the calculation to see if there is a saturday and/or a sunday from the startdate, by adding only the rest, or you could use the end dates day of week to determine this.

Good luck!

My blog on code, technology and tools in .NET and C#.

Dont forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
• TATWORTH

All-Star

44551 Points

13496 Posts

MVP

Re: How can I calculate the Number of Weekends between two dates

Try a function along the lines of

private int CalculateWeekends(DateTime DateTime1, DateTime DateTime2)
{
int iReturn = 0;
TimeSpan xTimeSpan;
if (DateTime2 > DateTime1)
xTimeSpan = DateTime2.Subtract(DateTime1);
else
xTimeSpan = DateTime1.Subtract(DateTime2);
int iDays = 5 + System.Convert.ToInt32(xTimeSpan.TotalDays);
iReturn = (iDays / 7);
return iReturn;
}

Click "Mark as Answer" on the post that helped you.
This earns you a point and marks your thread as Resolved so we will all know you have been helped.
FAQ on the correct forum http://forums.asp.net/p/1337412/2699239.aspx#2699239
• robert.weste...

Participant

1630 Points

368 Posts

Re: How can I calculate the Number of Weekends between two dates

Is the issue resolved? If so, please mark it as such, so that everyone knows not to read this thread as other than reference, and so that those with a similar problem knows they can use the thread as a reference. If the issue is not resolved, please keep up the communication and I'm sure you'll be helped in solving the issue.

My blog on code, technology and tools in .NET and C#.

Dont forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
• mikener

Member

63 Points

230 Posts

Re: How can I calculate the Number of Weekends between two dates

Sorry for the delay. I was out of the office. The formula appears to be close. I am just testing it now.

Once I get the correct answer I will post it.

• mikener

Member

63 Points

230 Posts

Re: How can I calculate the Number of Weekends between two dates

This method is close.  I haven't worked out why it does not work as of yet.

Using Start Date of 8/1/2007 and an End Date of 8/9/2007 this method correctly determines that there is one weekend between the two dates.

Using Start Date of 8/1/2007 and an End Date of 8/10/2007 this method incorrectly determines that there are two weekends between the two dates.

Using Start Date of 7/31/2007 and an End Date of 8/09/2007 this method incorrectly determines that there are two weekends between the two dates.

Any help would be much appreciated.

Thanks

• robert.weste...

Participant

1630 Points

368 Posts

Re: How can I calculate the Number of Weekends between two dates

It might not be the best solution considering performance, nor considering beauty of code, but I think it works (observe that the method includes the start day and excludes the end day):

```private const int MONDAY = 1;
private const int TUESDAY = 2;
private const int WEDNESDAY = 3;
private const int THURSDAY = 4;
private const int FRIDAY = 5;
private const int SATURDAY = 6;
private const int SUNDAY = 7;

/// <summary>
/// Observe that the method calculates by including the start day, but excludes the end day
/// </summary>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <returns></returns>
private void GetWeekendDaysBetween(DateTime startDate, DateTime endDate,out int saturdays,out int sundays)
{
saturdays = -1;
sundays = -1;
if (endDate < startDate)
return;
TimeSpan timeBetween = endDate.Subtract(startDate);
int weekendsBetween = timeBetween.Days / 7;
sundays = weekendsBetween;
saturdays = weekendsBetween;
int startDay = GetDayOfWeekNumber(startDate.DayOfWeek);
int endDay = GetDayOfWeekNumber(endDate.DayOfWeek);
if (startDay > endDay)
{
sundays++;
saturdays += (startDay < SUNDAY) ? 1 : 0;
}
else if (startDay < endDay)
{
//We don't have to care about sundays here, since we are excluding the last day
//There will only be another saturday, if the end day is a sunday
saturdays += (endDay == SUNDAY) ? 1 : 0;
}
}

/// <summary>
/// Since I don't think it's a good idea to rely on the face that the enums have specific values, I wrote this method
/// If you are satisfied with using the integer value of the enums, just remember that Sundays will then have the value 0
/// </summary>
/// <param name="day"></param>
/// <returns></returns>
private int GetDayOfWeekNumber(DayOfWeek day)
{
switch (day)
{
case DayOfWeek.Monday:
return MONDAY;
case DayOfWeek.Tuesday:
return TUESDAY;
case DayOfWeek.Wednesday:
return WEDNESDAY;
case DayOfWeek.Thursday:
return THURSDAY;
case DayOfWeek.Friday:
return FRIDAY;
case DayOfWeek.Saturday:
return SATURDAY;
case DayOfWeek.Sunday:
return SUNDAY;
default:
throw new ArgumentException("Invalid day!");
}
}```

My blog on code, technology and tools in .NET and C#.

Dont forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
• mikener

Member

63 Points

230 Posts

Re: How can I calculate the Number of Weekends between two dates

I will try to incorporate this into my code as soon as I get a chance.  There is one change that I noticed right off that while no big deal may or may note help you out.  The method GetDayOfWeekNumber does not need the switch statement. The method needs only one line:

return (int) day + 1;

This is not much of a help, but I thought that I should mention it.

Thanks again. As I said, I will test and mark this as answered as soon as I get chance (most likely tomorrow).

• robert.weste...

Participant

1630 Points

368 Posts

Re: How can I calculate the Number of Weekends between two dates

For two reasons, that wouldn't do good. First and foremost, sunday is 0 and monday is 1, and the rest of the code builds on the fact that sunday has the highest, not the lowest, number. The other reason is that I did not want to rely on the enum integers, as I wrote as comments in the text.

My blog on code, technology and tools in .NET and C#.

Dont forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
• mikener

Member

63 Points

230 Posts

Re: How can I calculate the Number of Weekends between two dates

Sorry for the mix up. I skimmed the code and not the comments.  I was in a hurry to give you some feedback before I had a chance to test the code.  My mistake. I tested the code. It works.

Thanks

• robert.weste...

Participant

1630 Points

368 Posts

Re: How can I calculate the Number of Weekends between two dates

It's okay. I actually like getting comments and feedback, so that I can improve. I am currently trying to work a lot on my grip on the english language so that I can use it better to be direct and consise without being rude or harsh. I apologize if my above post was considered as any of the latter.

My blog on code, technology and tools in .NET and C#.

Dont forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
• mikener

Member

63 Points

230 Posts

Re: How can I calculate the Number of Weekends between two dates

No problem. I really do appreciate the help.

Thanks again.

• robint84

Member

170 Points

45 Posts

Re: How can I calculate the Number of Weekends between two dates

The above code does not work well in all the situations. For example try the date range "2008, 1, 3" to  "2008, 1, 6".  This gives the answer 1(sum of saturdays and sundays) . But there are actually two weekend days in between.

• robert.weste...

Participant

1630 Points

368 Posts

Re: How can I calculate the Number of Weekends between two dates

Actually, the answer 1 is entirely correct. January 6th 2008 is a sunday. If you read the post which contains the code you'll see "(observe that the method includes the start day and excludes the end day)". Thus, it counts thursday, friday and saturday which means that, in the case of january 3rd to january 6th 2008, the sum of all saturdays and sundays is 1.

My blog on code, technology and tools in .NET and C#.

Dont forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
• robint84

Member

170 Points

45 Posts

Re: How can I calculate the Number of Weekends between two dates

I am really sorry. I didn't notice that. It works fine :)

• dst101

Member

43 Points

223 Posts

Re: How can I calculate the Number of Weekends between two dates

Sorry for being a Noob but how do you test this?

• TATWORTH

All-Star

44551 Points

13496 Posts

MVP

Re: How can I calculate the Number of Weekends between two dates

dst101

Sorry for being a Noob but how do you test this?

Functions like these are testable by unit testing frameworks like NUnit.  I will look up some tests for you this evening (UK time). Do you C# or VB.NET?

Also which version of Visual Studio are you using?

Click "Mark as Answer" on the post that helped you.
This earns you a point and marks your thread as Resolved so we will all know you have been helped.
FAQ on the correct forum http://forums.asp.net/p/1337412/2699239.aspx#2699239
• dst101

Member

43 Points

223 Posts

Re: How can I calculate the Number of Weekends between two dates

I was writing the code that was supplied in my code behind, and trying to call it in the page_load event but I'm getting errors, here's what I put:

lblDays.Text = GetWeekendDaysBetween(myStartDate, myEndDate);

And in the GetWeekendDaysBetween I put:

DateTime myStartDate = new DateTime(2009, 8, 1);//Added this
DateTime myEndDate = new DateTime(2009, 21, 1);//Added this

I'm using c# and VS 2008

Thanks!

• p23ghodake

Member

201 Points

81 Posts

Re: How can I calculate the Number of Weekends between two dates

Hi Rrobert

Regards
Pankaj Ghodake

Remember to click Mark as Answer on the post that helps to others.
• robert.weste...

Participant

1630 Points

368 Posts

Re: How can I calculate the Number of Weekends between two dates

Hi,

You write that you are getting errors, but you do not mention what errors you get. Could you please specify the errors you get and perhaps the rest of us can be of assistance to you.

Best regards
Robert

My blog on code, technology and tools in .NET and C#.

Dont forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
• dst101

Member

43 Points

223 Posts

Re: How can I calculate the Number of Weekends between two dates

Hi Robert,

The errors I get are:

The name 'myStartDate' does not exist in the current context
The name 'myEndDate' does not exist in the current context

DateTime myStartDate = new DateTime(2009, 8, 1);//Added this
DateTime myEndDate = new DateTime(2009, 21, 1);//Added this

And then tried to call it in the Page_Load event:
lblDays.Text = GetWeekendDaysBetween(myStartDate, myEndDate);

Now this is probably due to me not fully understanding on how to call the function properly, any chance you could supply the proper way to calling the function?

Sorry if this is a pain!

• robert.weste...

Participant

1630 Points

368 Posts

Re: How can I calculate the Number of Weekends between two dates

Hi,

You should not need to add anything to method itself. You should, however, create the startDate and endDate as well as declare the integers to hold the number of saturdays and sundays in your own method, before calling the GetWeekendDaysBetween, e.g.

```int numberOfSaturdays;
int numberOfSundays;
DateTime startDate = new DateTime(2009, 01, 08);
DateTime endDate = new DateTime(2009, 01, 21);
GetWeekendDaysBetween(startDate, endDate, out numberOfSaturdays, out numberOfSundays);```

Do remember that the DateTime constructor takes the parameters in the order (year, month, day) not (year, day, month).

If you would like to set the text of your control to be the total number of weekend days, add the following as the next code line:

`lblDays.Text = (numberOfSaturdays + numberOfSundays).ToString();`

Hope it helps!

/Robert

My blog on code, technology and tools in .NET and C#.

Dont forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
• dst101

Member

43 Points

223 Posts

Re: How can I calculate the Number of Weekends between two dates

Hi Robert,

Brilliant stuff! Many thanks.

Is it possible to put this code into a namespace? A big ask but thought I'd be cheeky anyway :)

Many thanks for looking at this!

Duncan

• p23ghodake

Member

201 Points

81 Posts

Re: How can I calculate the Number of Weekends between two dates

Hi Robert

It's Pankaj

Thanks for your code  and my end its works fine for SATURDAY, SUNDAY

I have some issue can you help me ?

1) Is this code work for MONDAY and FRIDAY?

2) If yes then how?

Actually I tried this my self but did not sucess,

Regards
Pankaj Ghodake

Remember to click Mark as Answer on the post that helps to others.
• dst101

Member

43 Points

223 Posts

Re: How can I calculate the Number of Weekends between two dates

<div class="dp-highlighter"><div class="bar"><div class="tools">

</div><div class="tools">view plaincopy to clipboardprint?
</div></div>
1. int numberOfSaturdays;
2. int numberOfSundays;
3. DateTime startDate = new DateTime(2009, 01, 08);
4. DateTime endDate = new DateTime(2009, 01, 21);
5. GetWeekendDaysBetween(startDate, endDate, out numberOfSaturdays, out numberOfSundays);
</div>
```int numberOfSaturdays;
int numberOfSundays;
DateTime startDate = new DateTime(2009, 01, 08);
DateTime endDate = new DateTime(2009, 01, 21);
GetWeekendDaysBetween(startDate, endDate, out numberOfSaturdays, out numberOfSundays);```

I thought I'd pop in a calendar and pick an enddate and the startdate being today, but I'm having difficulty converting the string back to DateTime mode, the problem seems to be that it's bringing the Time part back as well.

My question is can I omit the Time from the dates chosen in DateTime format?

Here is some of the code:

```   protected void CalendarEndDate_SelectionChanged(object sender, EventArgs e)
{

SelectedDatesCollection theEndDates = CalendarEndDate.SelectedDates;

DateTime TodaysDate = DateTime.Now;
DateTime SelectedDate = CalendarEndDate.SelectedDate;

lblCalDates.Text = SelectedDate.ToShortDateString();

int numberOfSaturdays;
int numberOfSundays;

/*get todays date and reformat it to yyyy/MM/dd*/
string TodaysDateAlt = TodaysDate.ToShortDateString();
DateTime startDate = Convert.ToDateTime(TodaysDateAlt);

lblMyDate.Text = startDate.ToString();

DateTime endDate = new DateTime(2009, 01, 21);
GetWeekendDaysBetween(startDate, endDate, out numberOfSaturdays, out numberOfSundays);
//return number of Saturdays and Sundays between the two specified dates
lblDays.Text = (numberOfSaturdays + numberOfSundays).ToString();
}```
Any pointers would be appreciated, DateTime is doing my head in :)

• p23ghodake

Member

201 Points

81 Posts

Re: How can I calculate the Number of Weekends between two dates

Hi try this..

1) Take two Canendar Contros and two text box controls

```DateTime startDate;
DateTime endDate;```

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
txtDate1.Text = Calendar1.SelectedDate.ToShortDateString(); // this take only Date (MM:DD:YYYY) stores in to text box as a string
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
txtDate2.Text = Calendar2.SelectedDate.ToShortDateString();  // this take only Date (MM:DD:YYYY) stores in to text box as a string
}

2) call  GetWeekendDaysBetween function

protected void btnCalculate_Click(object sender, EventArgs e)
{
startDate = Convert.ToDateTime(txtDate1.Text);  // this convert Date string in to Datetime
endDate = Convert.ToDateTime(txtDate2.Text);   // this convert Date string in to Datetime

GetWeekendDaysBetween(startDate,endDate,saturdays,sundays); // Call function
}

It works fine for me...

Regards
Pankaj Ghodake

Remember to click Mark as Answer on the post that helps to others.
• robert.weste...

Participant

1630 Points

368 Posts

Re: How can I calculate the Number of Weekends between two dates

dst101: Is it possible to put this code into a namespace?

I'm not certain I understand your question here. You are free to do anything you want with the code. Put it into your own namespace if you'd like to.

dst101: My question is can I omit the Time from the dates chosen in DateTime format?

Indeed, it is pretty easy, even. Just use the Date-property on your DateTime object. Example:

```This means that your code could be something similar to:
DateTime endDate = CalendarEndDate.SelectedDate.Date; //Using the .Date property might not be necessary here, but the cost is very small so why not? :)
DateTime startDate = DateTime.Now.Date;

int numberOfSaturdays;
int numberOfSundays;

GetWeekendDaysBetween(startDate, endDate, out numberOfSaturDays, out numberOfSundays);

lblDays.Text = (numberOfSaturdays + numberOfSundays).ToString();```

Hope it helps!

/Robert

My blog on code, technology and tools in .NET and C#.

Dont forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
• robert.weste...

Participant

1630 Points

368 Posts