Convert string to DateTime

I have a line like this:

"20090212" 

and I want to convert to actual C # datetime.

Does this need to be analyzed because it works too much?

+4
source share
3 answers

You can use DateTime.ParseExact :

 DateTime result = DateTime.ParseExact("20090212", "yyyyMMdd", CultureInfo.InvariantCulture); 
+13
source

Take a look at the DateTime.TryParseExact ( MSDN ) method. I prefer the TryParseExact method to the ParseExact method because it returns a boolean value indicating whether the conversion was successful instead of throwing an exception, but any of them will work.

+4
source
 DateTime.ParseExact(str, "yyyyMMdd", CultureInfo.CurrentCulture); 

... and I really doubt that I got there first.

Although for completeness I prefer TryParseExact

 DateTime dt; if(DateTime.TryParseExact(str, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out dt)) { // ... use the variable dt } 
+2
source

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


All Articles