简体   繁体   中英

Convert string to DateTime in c#

What is the easiest way to convert the following date created using

dateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture)

into a proper DateTime object?

20090530123001

I have tried Convert.ToDateTime(...) but got a FormatException .

Try this:

DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

If the string may not be in the correct format (and you wish to avoid an exception) you can use the DateTime.TryParseExact method like this:

DateTime dateTime;
DateTime.TryParseExact(str, "yyyyMMddHHmmss",
    CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);

http://msdn.microsoft.com/zh-CN/library/w2sa9yss.aspx

var date = DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)

这里的教程很好-我认为您只需要使用正确的格式字符串的ParseParseExact

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM