I consume a web service which returns me some dates as string, and I use DateTime.Parse
to get the correspondente DateTime
objects. It is working, but I'm afraid my usage of DateTime.Parse
may be vulnerable to bugs caused by different locale settings. The date returned is in the following format:
2014-04-24T00:00:00
The code I use to parse it:
DateTime d = DateTime.Parse(strValue);
Is there some way (such as passing a format provider, or using another method) in which I guarantee that my parsing routine will work regardless of the machine locale settings?
TryParse Method (System) Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.
Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information.
You are using the shortest form! Your format is ISO 8601-format (http://nl.wikipedia.org/wiki/ISO_8601). It is recognized with any culture!
So your way is the simplest way: DateTime result = DateTime.Parse("2008-06-15T21:15:07");
If you are not sure, use: DateTime result = DateTime.ParseExact("2008-06-15T21:15:07", "s", null);
Check out: http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx#properties
If you want to parse a date independent of the user's locale, then use the invariant culture:
DateTime d = DateTime.Parse(strValue, CultureInfo.InvariantCulture);
Since you have an exact format, I'd use a non-ambiguous format string:
DateTime.ParseExact("2014-04-24T00:00:00", "yyyy\\-MM\\-dd\\THH\\:mm\\:ss", null)
// or to reduce the C#-escaped backslashes:
DateTime.ParseExact("2014-04-24T00:00:00", @"yyyy\-MM\-dd\THH\:mm\:ss", null)
The escaped hyphens and colons, as well as the escaped T
, mean that those are constant values. So this line should work regardless of any other factors.
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