Add Days to DateTime based on condition using C# and VB.Net in ASP.Net

Last Reply one month ago By dharmendr

Posted one month ago

I have a date field in my database and on a button click i want to add 90 days to the date field.If the date is on a Saturday then I want to add 92 days to the date and if it is on a Sunday then I want to add 91 days to the date field. My code below is not working as expected. Any help would be appreciated.

Protected Sub btnReschedule_Click(sender As Object, e As EventArgs)
    Dim dueDate As DateTime
    dueDate = txtNextDueDate.Text
    If dueDate.DayOfWeek = DayOfWeek.Monday Or dueDate.DayOfWeek = DayOfWeek.Tuesday Or dueDate.DayOfWeek = DayOfWeek.Wednesday Or dueDate.DayOfWeek = DayOfWeek.Thursday Or dueDate.DayOfWeek = DayOfWeek.Friday Then
        txtNextDueDate.Text = DateTime.Now.AddDays(90).ToShortDateString
    End If
    If dueDate.DayOfWeek = DayOfWeek.Sunday Then
        txtNextDueDate.Text = DateTime.Now.AddDays(91).ToShortDateString
    End If
    If dueDate.DayOfWeek = DayOfWeek.Saturday Then
        txtNextDueDate.Text = DateTime.Now.AddDays(92).ToShortDateString
    End If
End Sub

 

You are viewing reply posted by: dharmendr one month ago.
Posted one month ago

Hi Tevin,

Check this example. Now please take its reference and correct your code.

HTML

<table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td>Data</td>
        <td><asp:TextBox ID="txtDate" runat="server" /></td>
    </tr>
    <tr>
        <td>Next DueDate</td>
        <td><asp:TextBox ID="txtNextDueDate" runat="server" /></td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnReschedule" Text="Reschedule" runat="server" OnClick="btnReschedule_Click" />
        </td>
    </tr>
</table>

C#

protected void btnReschedule_Click(object sender, EventArgs e)
{
    DateTime dueDate = Convert.ToDateTime(txtDate.Text);
    DateTime nextDueDate = dueDate.AddDays(90);
    if (nextDueDate.DayOfWeek == DayOfWeek.Sunday)
    {
        nextDueDate = dueDate.AddDays(91);
    }
    else if (nextDueDate.DayOfWeek == DayOfWeek.Saturday)
    {
        nextDueDate = dueDate.AddDays(92);
    }
    txtNextDueDate.Text = nextDueDate.ToString("dd/MM/yyyy");
}

VB.Net

Protected Sub btnReschedule_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim dueDate As DateTime = Convert.ToDateTime(txtDate.Text)
    Dim nextDueDate As DateTime = dueDate.AddDays(90)

    If nextDueDate.DayOfWeek = DayOfWeek.Sunday Then
        nextDueDate = dueDate.AddDays(91)
    ElseIf nextDueDate.DayOfWeek = DayOfWeek.Saturday Then
        nextDueDate = dueDate.AddDays(92)
    End If

    txtNextDueDate.Text = nextDueDate.ToString("dd/MM/yyyy")
End Sub

Screenshot