Strange Convert.ToDateTime behavior
Why is Convert.ToDateTime
behaving strangely for the following values?
The following works just fine:
var value = "08/01/2011";
var dateTime = Convert.ToDateTime(value);
The result is: {08/01/2011 00:00:00}
--- which is just expected.
But now, when I do this:
var value = "07/21/2011";
var dateTime = Convert.ToDa开发者_如何学CteTime(value);
I get an exception:
'Convert.ToDateTime("07/21/2011")' threw an exception of type 'System.FormatException'
"07/21/2011";
This is not a valid date, since 21
will be interpreted as the month.
Try explicitly specifying the format instead:
DateTime myDate = DateTime.ParseExact("07/21/2011", "MM/dd/yyyy",
CultureInfo.InvariantCulture);
Edit:
Agreed with @dtb's comment - I just couldn't find a culture where the date you specified is legal. But the general form is:
DateTime myDate = Convert.ToDateTime("07/21/2011", new CultureInfo("XXX"))
where XXX
is the name of the culture you want to use (i.e. "en-GB" - which won't work with this format though)
Date/time strings are parsed according to the culture settings for the current thread (which is determined by the regional settings made in the Windows Control Panel).
For example, if the current culture is fr-FR or en-GB, then the input is expected in day/month/year
format. If the current culture is en-US, the input is expected in month/day/year
format.
You can find the culture settings for the current thread by looking at the Thread.CultureInfo property of Thread.CurrentThread.
If you don't want to parse a date/time string according to the culture settings for the current thread, you have to specify the culture settings explicitly.
Your input seems to be in en-US format, while your system seems to be configured as fr-FR or en-GB. So explicitly specify en-US as culture:
DateTime result = DateTime.Parse("07/21/2011", new CultureInfo("en-US"));
// result.Day == 21
// result.Month == 7
// result.Year == 2011
The reason why your first example works, is because 1
is a valid month, unlike 21
.
DateTime result = DateTime.Parse("08/01/2011", new CultureInfo("fr-FR"));
// result.Day == 8
// result.Month == 1
// result.Year == 2011
精彩评论