How to correctly analyze DateTime in this format: "2013-04-29T00: 00: 00"

I use a web service that returns some dates to me as a string, and I use DateTime.Parseto get the corresponding objects DateTime. It works, but I'm afraid that my use DateTime.Parsemay be vulnerable to errors caused by various language settings. The returned date has the following format:

2014-04-24T00:00:00

The code I use to analyze it:

DateTime d = DateTime.Parse(strValue);

Is there any way (for example, passing the format provider or using another method) in which I guarantee that my parsing procedure will work regardless of the locale settings?

+5
source share
5 answers

! - ISO 8601- (http://nl.wikipedia.org/wiki/ISO_8601). !

, - : DateTime result = DateTime.Parse("2008-06-15T21:15:07");

, : DateTime result = DateTime.ParseExact("2008-06-15T21:15:07", "s", null);

: http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx#properties

+5

, , :

DateTime d = DateTime.Parse(strValue, CultureInfo.InvariantCulture);
+5

, :

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)

, T, , . - .

+1

, DateTime.ParseExact

string dateString, format;  
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;

dateString = "2013-04-29T00:00:00";
format = "s";

result = DateTime.ParseExact(dateString, format, provider);

Where the format string "s" represents a sortable DateTime (MSDN on Format Strings )

+1
source
  string dateString;
  DateTime dateValue;

  // Parse a string.
  dateString = "2014-04-24T00:00:00"; 
  if (DateTime.TryParseExact(dateString, "o",  CultureInfo.InvariantCulture, 
                DateTimeStyles.None, out dateValue))
   Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, 
             dateValue.Kind);
0
source

All Articles