Consider the following code:
class Program
{
static void Main(string[] args)
{
try
{
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("fo-FO");
var s = DateTime.MaxValue.ToString("yyyy-MM-ddTHH:mm:ssZ");
var d = DateTime.Parse(s, CultureInfo.InvariantCulture);
Console.WriteLine("Was able to parse with fo-FO");
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e);
}
try
{
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
var s = DateTime.MaxValue.ToString("yyyy-MM-ddTHH:mm:ssZ");
var d = DateTime.Parse(s, CultureInfo.InvariantCulture);
Console.WriteLine("Was able to parse with en-US");
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e);
}
}
}
The output is:
Exception: System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
at System.DateTime.Parse(String s, IFormatProvider provider)
at DateTimeTest2.Program.Main(String[] args) in C:\Projects\DateTimeTest2\DateTimeTest2\Program.cs:line 17
Was able to parse with en-US
This code fragment proves that DateTime.Parse uses Thread.CurrentThread.CurrentCulture regardless of the fact that the "InvariantCulture" is being passed in. I find this so unintuitive that I consider it a "bug".
Why do we have to pass in a CultureInfo if it is in fact ignored by DateTime.Parse in any case? Is there a way of calling DateTime.Parse in a way that is independent of the CurrentCulture?
This code fragment proves that DateTime.Parse uses Thread.CurrentThread.CurrentCulture regardless of the fact that the "InvariantCulture" is being passed in
I'm not sure how this example proves that. The strings passed to DateTime.Parse are different, so it's not completely surprising that different results ensue.
The first string has the time formatted as 23.59.59, which (apparently) InvariantCulture cannot parse; the second string has the time formatted as 23:59:59, which InvariantCulture can parse. What's the problem?
edit to add, since apparently it makes a difference, I am running with .NET 2.0 and the strings produced by fo-FO and en-US are respectively
9999-12-31T23.59.59Z
and
9999-12-31T23:59:59Z
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With