How to parse a string in DateTime with a specific format?

I have a source where dates go into this lowercase form:

   Sat Sep 22 13:15:03 2018

Is there an easy way I can parse this in a DateTime in C #? I tried using DateTime. (Try it), but it does not seem to recognize this particular format ...

+3
source share
4 answers

It works:

DateTime dt = DateTime.ParseExact ("Sat Sep 22 13:15:03 2018", "ddd MMM d HH:mm:ss yyyy", null)
+5
source

You should prefer DateTime.ParseExactand TryParseExact; These methods allow you to specify the expected format in your program.

DateTime.Parse TryParse , /, , , - - - . , Parse/TryParse.

+6

Try DateTime.ParseExact

This code takes your date string and applies the 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);
+5
source
var str = "Sat Sep 22 13:15:03 2018";
var date = DateTime.ParseExact(str, "ddd MMM dd HH:mm:ss yyyy", CultureInfo.InvariantCulture);
+4
source

Source: https://habr.com/ru/post/1724978/


All Articles