Pages

Friday 28 September 2012

How to compare two dates in "dd/MM/yyyy" format using CompareValidator in ASP.Net?

We usually don't get any error while comparing two date fields in "MM/dd/yyyy" format using CompareValidator. But, problem arises when the date fields are in "dd/MM/yyyy" format.
Suppose, we have a page where two textboxes are present(one for From Date and another for To Date) and a Button to submit the value. We are comparing the dates using a CompareValidator.
Source View:
<form id="form1" runat="server">
    <div>
        From Date :
        <asp:TextBox ID="txtFromDate" runat="server"></asp:TextBox>
    </div>
    <div>
        To Date :
        <asp:TextBox ID="txtToDate" runat="server"></asp:TextBox>
        <asp:CompareValidator ID="compDate" runat="server" ControlToValidate="txtToDate"
            ControlToCompare="txtFromDate" ErrorMessage="From date should be less than To
            date !" Operator="GreaterThanEqual" SetFocusOnError="true" Type="Date"> 
        </asp:CompareValidator>
    </div>
    <div>
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    </div>
</form>
Design View:

Now, it will work properly if we are entering values in "MM/dd/yyyy" format. But, if we enter values in "dd/MM/yyyy" format and especially dates greater than 12, it won't work properly and will give wrong output.

To get rid out of this problem, you just need to change your Page Culture whose default date format is "dd/MM/yyyy". Here, I have changed the Culture to "en-GB" and it worked properly.
protected void Page_Load(object sender, EventArgs e)
{
        Page.Culture = "en-GB";
}

Output:


Regards,
Prajanuranjan....

2 comments:

  1. Good day! Do you turn to get extra help to any specific tricks to get more followers for this site? Can't wait to hear from you.

    ReplyDelete
  2. Thanks This worked for Me....

    ReplyDelete

Total Pageviews