Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date and time string to DateTime in C# [duplicate]

I have string that displays date and time in the following format:

Thu Jan 03 15:04:29 2013

How would I convert this to a DateTime? I have tried:

string strDateStarted = "Thu Jan 03 15:04:29 2013"
DateTime datDateStarted = Convert.ToDateTime(strDateStarted);

But this does not work. In my program this value is read in from a log file so I am not able to change the format of the text string.

like image 708
TroggleDorf Avatar asked Dec 07 '22 08:12

TroggleDorf


1 Answers

Use one of the *Parse* methods defined on DateTime.

Either TryParseExact or ParseExact which will take a format string corresponding to the date string.

I suggest reading up on Custom Date and Time Format Strings.

In this case, the corresponding format string would be:

"ddd MMM dd HH:mm:ss yyyy"

To be used:

DateTime.ParseExact("Thu Jan 03 15:04:29 2013", 
                    "ddd MMM dd HH:mm:ss yyyy", 
                    CultureInfo.InvariantCulture)
like image 88
Oded Avatar answered Jan 05 '23 01:01

Oded