使用ParseExact进行转换时,字符串无法识别为有效的日期时间

时间:2016-10-21 20:39:46

标签: c# datetime

我正在尝试取一个字符串并将其转换为DateTime,但无论我尝试什么,我总是得到

  

字符串未被识别为有效的DateTime

我正在尝试使用DateTime.ParseExact,但无论我传入的格式字符串是什么,我总是会收到此错误。我累了将我正在转换的变量分配给一个字符串以确认格式,然后它将返回

10/11/2016 10:04:51 AM

我在这里缺少什么?

var excelFile = new ExcelQueryFactory(path);

var culture = new CultureInfo("en-US", true);

var excelData = excelFile.WorksheetRange("A6", "N16384", "Alarm Report")
                            .Select(row => new MTNAlarm()
                            {
                                AlarmDescription = row["Raised"],
                                //AlarmStatus = row["Alarm Status"],
                                //ContainingFolder = row["Containing Folder"],
                                //DeviceName = row["Device Name"],
                                //DeviceType = row["Device Type"],
                                //FullPath = row["Full Device Path"],
                                //IPAddress = row["IP Address"],
                                //IsCleared = (row["Cleared"] == "N/A") ? true : false,
                                //IsIgnored = (row["Ignored"] == "N/A") ? true : false,
                                //IsTrap = (row["Is Trap"] == "True") ? true : false,
                                Raised = DateTime.ParseExact(row["Raised"], "MM/dd/yyyy h:mm:ss tt", culture),
                                //Severity = row["Severity"],
                                //SitePortalAlarmID = int.Parse(row["Alarm ID"]),
                                //LocationID = 0,
                            }).ToList();

我试过了:

MM/dd/yyyy h:mm:ss tt
MM/dd/yyyy hh:mm:ss tt
MM/dd/yyyy HH:mm:ss tt
MM/dd/yyyy HH:mm

2 个答案:

答案 0 :(得分:2)

处理Excel日期时,日期可以存储为日期的字符串表示形式,也可以是OA date(OLE自动化日期)。我发现在解析Excel日期时检查这两种类型是最安全的路径。

这是我为转换编写的扩展方法:

/// <summary>
/// Sometimes the date from Excel is a string, other times it is an OA Date:
/// Excel stores date values as a Double representing the number of days from January 1, 1900.
/// Need to use the FromOADate method which takes a Double and converts to a Date.
/// OA = OLE Automation compatible.
/// </summary>
/// <param name="date">a string to parse into a date</param>
/// <returns>a DateTime value; if the string could not be parsed, returns DateTime.MinValue</returns>
public static DateTime ParseExcelDate( this string date )
{
    DateTime dt;
    if( DateTime.TryParse( date, out dt ) )
    {
        return dt;
    }

    double oaDate;
    if( double.TryParse( date, out oaDate ) )
    {
        return DateTime.FromOADate( oaDate );
    }

    return DateTime.MinValue;
}

在您的示例中,用法为:

Raised = row["Raised"].ParseExcelDate()

根据文化,您可能需要修改扩展方法以满足您的需求。

答案 1 :(得分:0)

var dt = DateTime.ParseExact("10/11/2016 10:04:51 AM", 
                             "MM/dd/yyyy hh:mm:ss tt",
                             CultureInfo.InvariantCulture);