Convert String value format of YYYYMMDDHHMMSS to C# DateTime

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

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?

回答1:

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



回答2:

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); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!