Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if begindate is weekend

Tags:

c#

I need to check if the selected date from a datepicker is not on a weekend. The function needs to keep checking if the new startdate is a weekend. Also it need to add days to the startdate if a weekend occurs.

Code should be something like this:

int startday = Datepicker1.SelectedDate;
if (startdate = weekendday, startdate++)
{
 startdate++ //or if a sunday +2
}
else
{
 return startdate
}

Thank you for your help.

like image 830
Dave Avatar asked Oct 08 '12 12:10

Dave


2 Answers

if (startdate.DayOfWeek == DayOfWeek.Saturday)
    startdate = startdate.AddDays(2);
else if (startdate.DayOfWeek == DayOfWeek.Sunday)
    startdate = startdate.AddDays(1);
like image 74
M4N Avatar answered Oct 30 '22 18:10

M4N


Using the DayOfWeek property you can explicitly check for weekend days. Something like this:

if ((startDate.DayOfWeek == DayOfWeek.Saturday) ||
    (startDate.DayOfWeek == DayOfWeek.Sunday))

Of course, that's a bit long for a conditional. Abstracting it to a helper method makes it a little cleaner:

private bool IsWeekend(DateTime date)
{
    return (date.DayOfWeek == DayOfWeek.Saturday) ||
           (date.DayOfWeek == DayOfWeek.Sunday)
}

To use like this:

if (IsWeekend(startDate))

Or, perhaps a little cleaner, you could write an extension method for DateTime:

public static bool IsWeekend(this DateTime date)
{
    return (date.DayOfWeek == DayOfWeek.Saturday) ||
           (date.DayOfWeek == DayOfWeek.Sunday)
}

Which you would use like this:

if (startDate.IsWeekend())
like image 25
David Avatar answered Oct 30 '22 16:10

David