The error shown in question might have been thrown by
Convert.ToDateTime
method as shown below:
string dateString = @"20/05/2012";
DateTime date = Convert.ToDateTime(dateString);
In the above code the
dateString
represents
Date
in the
Day/Month/Year
format.
By default the
en-US
culture is used by
.NET
according to which the
Date
is in
Month/Day/Year
format. So, when
ToDateTime
method is used it throws error as 20 is out of
Month
range.
To avoid this error the appropriate culture can be used as follows
string dateString = @"20/05/2012";
DateTime date2 = Convert.ToDateTime(dateString,
System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
Or the
ParseExact
method can be used with the required custom format as shown below:
string dateString = @"20/05/2012";
DateTime date3 = DateTime.ParseExact(dateString, @"d/M/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
Here
d/M/yyyy
matches both single and double digit months, days like
20/05/2012, 20/5/2012.
The custom format is used in conjunction with
InvariantCulture
.
When
TryParse
method is used as shown below
DateTime date4;
string dateString = @"20/05/2012";
bool result = DateTime.TryParse(dateString,out date4);
the parsing fails, but it will not throw error, rather it returns
false
indicating that the
parsing failed.