Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string with date and time to DateTime data type?

A client is sending a string containing a date in format YYYYMMDDHHmmSS (e.g. 201004224432). There are no separators like / or -.

How can I easily convert this to a DateTime object? Convert.ToDateTime() does not work.

like image 820
Vishal Avatar asked Nov 29 '22 18:11

Vishal


2 Answers

Use DateTime.ParseExact:

var date = DateTime.ParseExact(
                       "201004224432", 
                       "yyyyMMddHHmmss",
                       CultureInfo.InvariantCulture);

Note the tweaks to your format string to work appropriately.

like image 81
Reed Copsey Avatar answered Dec 17 '22 00:12

Reed Copsey


You want DateTime.ParseExact, which can take in a formatting string like yours and use it to parse the input string.

like image 30
Matt Greer Avatar answered Dec 16 '22 22:12

Matt Greer