sl3dg3
sl3dg3

Reputation: 5180

TryParse special date-format

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

Upvotes: 8

Views: 3454

Answers (5)

Akram Shahda
Akram Shahda

Reputation: 14771

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.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499860

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);

Upvotes: 13

Roy Dictus
Roy Dictus

Reputation: 33139

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

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

Upvotes: 1

Adi
Adi

Reputation: 5223

Try this

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

Without using "T".

Upvotes: 2

Mubashir Khan
Mubashir Khan

Reputation: 1494

you can use DateTime.TryParseExact instead.

How to create a .NET DateTime from ISO 8601 format

Upvotes: 2

Related Questions