Compare dd/MM/yyyy format date string with current Date in C# and VB.Net

Last Reply on Sep 16, 2014 02:38 AM By mosin

Posted on Sep 15, 2014 07:11 AM

Please tell me how can i compare user input date in format M/d/yyyy with System.DateTime.Now? Please provide demo for the same.

Posted on Sep 16, 2014 02:38 AM

I am providing demo with Textbox having date i.e. 16/09/2014 on button click event it's compare System DateTime. Convert Datetime function uses CultureInfo() to convert string to datetime format.

Please refer the following code:

HTML

<div>
    <asp:TextBox ID="txtDate" runat="server" Text="16/09/2014"></asp:TextBox>
    <asp:Button ID="btnCompare" Text="Compare" runat="server" OnClick="Compare" />
    <br />
    <asp:Label ID="lblMessage" runat="server"></asp:Label>
</div>

Namespace

using System.Globalization;

C#

protected void Compare(object sender, EventArgs e)
{
    DateTime currentDate = DateTime.Now;
    DateTime compareDate = Convert.ToDateTime(this.txtDate.Text.Trim(), new CultureInfo("en-GB"));
    string message = string.Empty;
    if (currentDate > compareDate)
    {
        message = "Current date is greater than input date";
    }
    if (currentDate < compareDate)
    {
        message = "Current date is less than input date";
    }
    if (currentDate == compareDate)
    {
        message = "Current date is equal to input date";
    }
    ClientScript.RegisterClientScriptBlock(typeof(string),"message","alert('"+message+"')",true);
}

Namespace

Imports System.Globalization

VB.Net

Protected Sub Page_Load(sender As Object, e As EventArgs)
    If Not Me.IsPostBack Then
        Me.txtDate.Text = "16/09/2014"
    End If
End Sub

Protected Sub Compare(sender As Object, e As EventArgs)
    Dim currentDate As DateTime = DateTime.Now
    Dim message As String = String.Empty
    If currentDate > compareDate Then
        message = "Current date is greater than input date"
    End If
    If currentDate < compareDate Then
        message = "Current date is less than input date"
    End If
    If currentDate = compareDate Then
        message = "Current date is equal to input date"
    End If
    ClientScript.RegisterClientScriptBlock(GetType(String), "message", (Convert.ToString("alert('") & message) + "')", True)
End Sub