+1 vote
26 views

How do you convert a string such as 2009-05-08 14:40:52,531 into a DateTime?

@dban Why a response from @CMS not marked as an answer? There may be a reason -I'm curious.

2 Answers

+1 vote

This worked for me:

CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dt = DateTime.ParseExact("2009-05-08 14:40:52,531","yyyy-MM-dd HH:mm:ss,fff", provider);
0 votes

Do you want it fast?

Let's say you have a date with format yyMMdd.

The fastest way to convert it that I found is:

var d = new DateTime(
(s[0] - '0') * 10 + s[1] - '0' + 2000, 
(s[2] - '0') * 10 + s[3] - '0', 
(s[4] - '0') * 10 + s[5] - '0')

Just, choose the indexes according to your date format of choice. If you need speed probably you don't mind the 'non-generic' way of the function.

This method takes about 10% of the time required by:

var d = DateTime.ParseExact(s, "yyMMdd", System.Globalization.CultureInfo.InvariantCulture);
...