Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly parse a DateTime in this format: "2013-04-29T00:00:00" [duplicate]

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?

like image 543
Doug Avatar asked Apr 29 '13 19:04

Doug


People also ask

How do you parse DateTime?

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.

What does DateTime parse () do in C#?

Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information.


3 Answers

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

like image 161
Martin Mulder Avatar answered Nov 14 '22 21:11

Martin Mulder


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);
like image 29
cdhowie Avatar answered Nov 14 '22 21:11

cdhowie


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.

like image 36
Joe Enos Avatar answered Nov 14 '22 22:11

Joe Enos