8

I try to parse a date-time stamp from an external system as following:

DateTime expiration;
DateTime.TryParse("2011-04-28T14:00:00", out expiration);

Unfortunately it is not recognized. How can I parse this successfully?

sl3dg3

sl3dg3
  • 5,026
  • 12
  • 50
  • 74

5 Answers5

13

Specify the exact format you want in DateTime.TryParseExact:

DateTime expiration;

string text = "2011-04-28T14:00:00";
bool success = DateTime.TryParseExact(text,
                                      "yyyy-MM-ddTHH:mm:ss",
                                      CultureInfo.InvariantCulture,
                                      DateTimeStyles.None,
                                      out expiration);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

you can use DateTime.TryParseExact instead.

How to create a .NET DateTime from ISO 8601 format

Community
  • 1
  • 1
Mubashir Khan
  • 1,464
  • 1
  • 12
  • 17
2

Try this

DateTime expiration;
DateTime.TryParse("2011-04-28 14:00:00", out expiration); 

Without using "T".

Adi
  • 5,113
  • 6
  • 46
  • 59
  • Changing the input value (which is supplied elsewhere) isn't nearly as nice a solution as changing how you parse to match the expected format, IMO. – Jon Skeet Apr 28 '11 at 10:16
1

You need to append "00000Z" to your string argument.

DateTime.TryParse("2011-04-28T14:00:0000000Z", out expiration);
Roy Dictus
  • 32,551
  • 8
  • 60
  • 76
1

User DateTime.TryParseExact function as following:

DateTime dateValue;

if (DateTime.TryParseExact(dateString, "yyyy-MM-ddTHH:mm:ss", 
                              new CultureInfo("en-US"), 
                              DateTimeStyles.None, 
                              out dateValue))
{
    // Do Something ..
}

Read about DateTime.

Akram Shahda
  • 14,655
  • 4
  • 45
  • 65