将字符串转换为DateTime在C#

将字符串转换为DateTime在C#

问题描述:

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

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

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

插入合适的的DateTime 对象?

20090530123001

我曾尝试 Convert.ToDateTime(...),但有一个 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);