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.
if (startdate.DayOfWeek == DayOfWeek.Saturday)
startdate = startdate.AddDays(2);
else if (startdate.DayOfWeek == DayOfWeek.Sunday)
startdate = startdate.AddDays(1);
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With