validation – Writing an IsDate() equivalent in C#?

validation – Writing an IsDate() equivalent in C#?

Did you check out DateTime.TryParse()s alternative override where it gives you a lot more control over what it considers to be a date?

Consider using DateTime.TryParseExact

validation – Writing an IsDate() equivalent in C#?

To convert string to date You either specify a culture that uses that specific format :
like we want to convert string date dd/MM/yyyy to Date..

datetime mydate = Convert.ToDateTime(
txtdate.Text, CultureInfo.GetCulture(en-GB)
);

or use the ParseExact method:

datetime mydate = DateTime.ParseExact(
txtdate.Text, dd/MM/yyyy, CultureInfo.Invariant
);

The ParseExact method only accepts that specific format, while the Convert.ToDateTime method still allows some variations on the format, and also accepts some other date formats.

To catch illegal input, you can use the TryParseExact method:

DateTime d;
if (DateTime.TryParseExact(txtdate.Text, dd/MM/yyyy, CultureInfo.Invariant, DateTimeStyles.None, out d)) {
datetime mydate = d;
} else {
// communcate the failure to the user
} 

I hope below links will provide you some help:

http://dotnetacademy.blogspot.com/2010/09/convert-string-to-date.html

http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx

http://msdn.microsoft.com/en-us/library/9h21f14e.aspx

http://dotnetacademy.blogspot.com/2009/10/get-current-system-date-format.html

This is a Example for tryParse :
http://dotnetperls.com/datetime-tryparse

Leave a Reply

Your email address will not be published.