Check if DateTime is Weekend or public Holiday using C# and VB.Net in ASP.Net

Last Reply 5 months ago By pandeyism

Posted 5 months ago

I have a form and on a button click i automatically generate a date exactly a year in the future. I would like to know how to make sure that this date is not on a public holiday or on a weekend. Any help please ?

Posted 5 months ago

Hi Tevin,

Take reference to below code according to your requirement write insert code after checking condition.

Define your public Holidays Date in the Array.

Code

C#

protected void Generate(object sender, EventArgs e)
{
    var publicHolidays = new[]
{
    new DateTime(2019, 1, 1),
    new DateTime(2019, 1, 26), 
    new DateTime(2019, 3, 4),
    new DateTime(2019, 4, 6),
    new DateTime(2019, 4, 19),
    new DateTime(2019, 5, 1)
};

    DateTime start = new DateTime(2019, 01, 01);
    foreach (var item in publicHolidays)
    {
        if (item != start && item.DayOfWeek != DayOfWeek.Saturday && item.DayOfWeek != DayOfWeek.Sunday)
        {

        }
    }
}

VB.Net

Protected Sub Generate(ByVal sender As Object, ByVal e As EventArgs)
    Dim publicHolidays = {New DateTime(2019, 1, 1), New DateTime(2019, 1, 26), New DateTime(2019, 3, 4), New DateTime(2019, 4, 6), New DateTime(2019, 4, 19), New DateTime(2019, 5, 1)}
    Dim start As DateTime = New DateTime(2019, 1, 1)
    For Each item In publicHolidays
        If item <> start AndAlso item.DayOfWeek <> DayOfWeek.Saturday AndAlso item.DayOfWeek <> DayOfWeek.Sunday Then
        End If
    Next
End Sub