Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

Tags:

c#

datetime

I have a need to convert a string value in the form "YYYYMMDDHHMMSS" to a DateTime. But not sure on how, may be a DateTime.Tryparse can be used to make this happen. Or is there any other way to do it. I can do this using some string operations to take "YYYYMMDD" alone, convert to a datetime and then add HH, MM, SS separately to that DateTime. But is there any DateTime.TryParse() methods that I can use in one line to convert a "YYYYMMDDHHMMSS" format string value to a DateTime value?

like image 638
SARAVAN Avatar asked Jun 11 '10 20:06

SARAVAN


People also ask

How do I convert a DateTime to a specific format?

The ToString() method of the DateTime class is used to convert a DateTime date object to string format. The method takes a date format string that specifies the required string representation.

How do I get yyyyMMddHHmmss in C#?

You can use a custom format string: DateTime d = DateTime. Now; string dateString = d. ToString("yyyyMMddHHmmss");


2 Answers

Define your own parse format string to use.

string formatString = "yyyyMMddHHmmss"; string sample = "20100611221912"; DateTime dt = DateTime.ParseExact(sample,formatString,null); 

In case you got a datetime having milliseconds, use the following formatString

string format = "yyyyMMddHHmmssfff" string dateTime = "20140123205803252"; DateTime.ParseExact(dateTime ,format,CultureInfo.InvariantCulture); 

Thanks

like image 184
Mikael Svenson Avatar answered Sep 21 '22 05:09

Mikael Svenson


You have to use a custom parsing string. I also suggest to include the invariant culture to identify that this format does not relate to any culture. Plus, it will prevent a warning in some code analysis tools.

var date = DateTime.ParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture); 
like image 35
Pierre-Alain Vigeant Avatar answered Sep 23 '22 05:09

Pierre-Alain Vigeant