Tutorial :how to validate dates in asp.net



Question:

I have been having this issue with dates since "ever"

I live in a country where we use the british date formats e.g. dd/mm/yyyy but everytime I try to do a query to a sql db hosted in a US server, 100% of the time I come accross to errors.

Convert.ToDateTime("2007-17-5") produces an error where as Convert.ToDateTime("2007-5-17") also produces an error.

Many validation methods, many t-sql queries and many other ways I've tried and solved partially in most of my projects however, I would like to know if anyone out there has a universal way of converting strings to a date that would not cause any problems?

or any good resources regarding working with dates ?

----------- editing... -----------------

even if I format the dates correctly, the query to the sql server doesn not produce any value even if I am sure that there are.. for example.. if I am searching for the records that belongs to dates between 1/1/2009 (that is 1 Jan 2009) through 1/5/2009 (that is 1 MAY 2009) no records are returned. And when I try to change the date in the query builder of the sql server, it gives me an error saying its not a valid date that I am entering...


Solution:1

2007-5-17 is not a valid International Date (ISO 8601), 2007-05-17 is. If you are going to be using the International format CCYY-MM-DD you need to include the leading 0s

http://www.w3.org/QA/Tips/iso-date

http://www.saqqara.demon.co.uk/datefmt.htm


Solution:2

Use DateTime.TryParseExact and give some format, that represent your date string


Solution:3

You handle a lot date validation of this in the UI.

First, in your webconfig, you need to set your culture:

<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="en-GB" uiCulture="en-GB" />  

You can use the CompareValidator control on the client side with by setting the Type attribute to "Date".

<CompareValidator ID="id" runat="server"    ControlToValidate="controltovalidateid"    ErrorMessage="Invalid Date"    Type="Date" />  

To limit the users options I've used the calendar control in the ASP.NET. One nice thing about that control is you can set the date format in the attribute:

<ajaxToolkit:Calendar runat="server"    TargetControlID="Date1"    CssClass="ClassName"    Format="dd/mm/yyyy"    PopupButtonID="Image1" />  

Other information


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »