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...
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...
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);
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
.
var str = "Sat Sep 22 13:15:03 2018";
var date = DateTime.ParseExact(str, "ddd MMM dd HH:mm:ss yyyy", CultureInfo.InvariantCulture);
This works:
DateTime dt = DateTime.ParseExact ("Sat Sep 22 13:15:03 2018", "ddd MMM d HH:mm:ss yyyy", null)