Friday, November 11, 2011

C# : Parsing dates


Dates are a PIA – no matter what language.

Found a neat way to do the validation e.g. the d/m/yyyy vs. d/mm/yyyy vs. dd/mm/yyyy etc.

bool validDate = DateTime.TryParseExact(txtDate.Text, 
new[] { "dd/MM/yyyy", "d/MM/yyyy"},
CultureInfo.InvariantCulture, DateTimeStyles.None, out d);

if (!validDate)
Error stuff
Valid stuff

So you just add the valid patterns to the array and away you go!


No comments: