compareValidator use with DateTime

I have been refactoring my colleague code recently. His code does the following, get user filter inputs and two dates for defining data within that two dates is retrieved.
I told him to use the AjaxToolKit calendarExtender and he did. He then does a lot checking in server-side to validate the user input dates. It is okay but with two points I think we can make some improvement.We should have client-side validation to improve user experience and clean up those code-behide checkings cause those if…return is making a big mess.

I rather use the compareValidator to do those dirty work for me and so I do. Here is two common techniques, check if the date is validate and check the begin date must be previous to the end date.

1. Check validate date : Type=”Date” and Operator=”DateTypeCheck”

<asp:CompareValidator ID="vld_startDate" runat="server" ErrorMessage="invalid date format" Type="Date"
                        Operator="DataTypeCheck" ControlToValidate="tb_startDate"></asp:CompareValidator>

2. Compare two date : Type=”Date”, Operator=”LessThanEqual”, i.e ControlToValidate LessThanEqual to ControlToCompare

<asp:CompareValidator ID="vld_compareDate" runat="server" ErrorMessage="begin date must be smaller than end date"
                        Type="Date" ControlToValidate="tb_startDate" ControlToCompare="tb_endDate" Operator="LessThanEqual"></asp:CompareValidator>

These techniques are simple but comes handy when you need them. Cheers.


C# Use DateTime.ParseExact() instead of DateTime.Parse()

I didn’t notice this until today, the DateTime I retrieve from my database has the format of yyyy/MM/dd hh:mm:ss.fff

and if I use DateTime.Parse(), the .fff value will be lost.

After searching google, I find out that not only DateTime.Parse() has this one problem, it also has problem with culture setting.

So, whenever you what to parse a DateTime, use DateTime.ParseExact().

Here is an useful example :

string[] DateTimeList = {
                            "yyyy/M/d tt hh:mm:ss",
                            "yyyy/MM/dd tt hh:mm:ss",
                            "yyyy/MM/dd HH:mm:ss",
                            "yyyy/M/d HH:mm:ss",
DateTime dt = DateTime.ParseExact(" 2008/  3/18   PM 02: 50:23  ",

Remember, CultureInfo is important to parsing, for example tt in Chinese will be 上午/下午, in en-US will be AM/PM. You can use CultureInfo.CreateSpecificCulture() to create the culture you need.
A small pattern reference

yyyy year ‘2009’
MM month ’04’
dd day ’17’
HH 24 hour ’23’
hh 12 hour ’11’
mm minutes ’59’
ss seconds ’30’
tt AM/PM
zzz GMT