CalvinBlount
CalvinBlount

Reputation: 155

Converting String Format "yyyy-MM-ddTHH:mm:ss.fffZ" to DateTime

I know this question has been asked a number of different ways, and I have looked at them all and none of the solutions seem to work for me. So, I am hoping that maybe you guys can give me a quick hand.

The input string is: "2000-01-01T12:00:000Z". I need to take that input string and convert it to DateTime so that it can be stored in the database.

I have been using ParseExact, but I keep getting the not recognized date string exception. Where am I going wrong?

inValue.LatestDepartTime = "2000-01-01T12:00:000Z";
DateTime _latestDepartTime = DateTime.ParseExact(inValue.LatestDepartTime, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);

Upvotes: 13

Views: 48266

Answers (5)

Mohammad f
Mohammad f

Reputation: 1061

Use yyyy-MM-dd'T'HH:mm:ss.fff'Z'

The code is:

public DateTime convertIsoToDateTime (string iso)
{
    return DateTime.ParseExact(iso, "yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
}

Upvotes: 10

inciph
inciph

Reputation: 31

You need to put single quotes around the T and Z:

DateTime parsedDateTime;
DateTime.TryParseExact(obj, "yyyy-MM-dd'T'HH:mm:ss'Z'", null, System.Globalization.DateTimeStyles.None, out parsedDateTime);
return parsedDateTime;

Upvotes: 3

dan04
dan04

Reputation: 91015

You need to include \\T and \\Z in your format string to match the literals T and Z.

Upvotes: 5

SLaks
SLaks

Reputation: 887459

Your format string needs to exactly match the input.

That includes the literal T and Z characters.

Upvotes: 9

Lucero
Lucero

Reputation: 60190

You don't specify the T in the pattern.

That said, you may want to have a look at the XmlConvert class, which provides the methods for converting this format.

Upvotes: 3

Related Questions