Captain Comic
Captain Comic

Reputation: 16206

How to parse datetime with DateTime.ParseExact

I have the following string that I need to parse

string date = "2017-06-23T13:45:45.816"

What is correct format string?

I tried

DateTime createDate = DateTime.ParseExact(date, "yyyy-MM-dd'T'hh-mm-ss", CultureInfo.InvariantCulture);

Upvotes: 0

Views: 1203

Answers (3)

Atul R
Atul R

Reputation: 51

Firstly You should Replace That 'T' With Blank Space ' '

string date = "2017-06-23T13:45:45.816";

date = date.Replace("T"," ");    // you can use this code to replace

 DateTime myDate = DateTime.ParseExact(date, "yyyy-MM-dd HH:mm:ss,fff",                                        System.Globalization.CultureInfo.InvariantCulture);

 Console.WriteLine(myDate.ToString("yyyy-MM-dd HH:mm:ss.fff")); 

// you can try this code might be it works for u

Upvotes: 0

Lloyd
Lloyd

Reputation: 29668

yyyy-MM-dd'T'hh-mm-ss is not 2017-06-23T13:45:45.816 you have missing milliseconds, 12 hour clock and also wrong separators.

You'd probably need something like:

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

Remember it's ParseExact.

Upvotes: 7

Patrick Hofman
Patrick Hofman

Reputation: 157038

That seems an RFC 3339 date to me, so Convert.ToDateTime or DateTime.Parse will do.

string date = "2017-06-23T13:45:45.816";
DateTime dt = Convert.ToDateTime(date);

Upvotes: 5

Related Questions