在c#中将字符串转换为DateTime

在c#中将字符串转换为DateTime

问题描述:

转换以下使用创建的日期的最简单方法是什么

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

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

转换成一个合适的 DateTime 对象?

into a proper DateTime object?

20090530123001

我尝试过 Convert.ToDateTime(...) 但得到了 FormatException.

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

试试这个:

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

如果字符串的格式可能不正确(并且您希望避免出现异常),您可以像这样使用 DateTime.TryParseExact 方法:

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