views:

153

answers:

5

Hi! I have a source where dates comes in this string form:

   Sat Sep 22 13:15:03 2018

Is there any easy way I can parse that as a datetime in C#? I've tried with DateTime.(Try)Parse, but it doesn't seem to recognize this specific format...

A: 

It looks like C# can parse it normally, ignore this.

William
+5  A: 

Try DateTime.ParseExact

This code takes your date string and applies a format to create a DateTime object.

CultureInfo provider = CultureInfo.InvariantCulture;

string dateString = "Sat Sep 22 13:12:03 2018";
string format = "ddd MMM dd HH':'mm':'ss yyyy";

DateTime result = DateTime.ParseExact(dateString, format, provider);
Robert Greiner
This is missing the numeric day of the month after the abbreviated month name. See my answer.
Gonzalo
You're right I fixed it, thanks.
Robert Greiner
+5  A: 

You should prefer DateTime.ParseExact and TryParseExact; these methods let you specify the expected format(s) in your program.

The DateTime.Parse and TryParse methods are dangerous because they accept the current date/time format configured on the machine where the code is running -- which the user can change from the default -- along with a couple of culture-neutral formats. In other words, the user can change settings in Control Panel and break Parse/TryParse.

Tim Robinson
+4  A: 
var str = "Sat Sep 22 13:15:03 2018";
var date = DateTime.ParseExact(str, "ddd MMM dd HH:mm:ss yyyy", CultureInfo.InvariantCulture);
Darin Dimitrov
+4  A: 

This works:

DateTime dt = DateTime.ParseExact ("Sat Sep 22 13:15:03 2018", "ddd MMM d HH:mm:ss yyyy", null)
Gonzalo
Thanks a lot! Should have found it myself...
Dan Pettersson