Convert.ToDateTime函数出错,错误为" String未被识别为有效的DateTime"

时间:2014-04-09 05:26:50

标签: c# datetime

这是我的代码:

private void GenerateExcelDataToday()
{
    try
    {
        // Setting path for the Excel File
        string path = System.IO.Path.GetFullPath(Server.MapPath("~/Closure.xlsx"));

        if (Path.GetExtension(path) == ".xls")
        {
            oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
        }
        else if (Path.GetExtension(path) == ".xlsx")
        {
            oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
        }

        oledbConn.Open();

    }
    catch (Exception ex)
    {
        lblError.Text = ex.ToString();
    }
    finally
    {
        oledbConn.Close();
    }

    ClosureReport();
}

private void ClosureReport()
{
    OleDbCommand cmd = new OleDbCommand();
    OleDbDataAdapter oleda = new OleDbDataAdapter();
    DataSet ds = new DataSet();

    cmd.Connection = oledbConn;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT * FROM [Data$]";
    oleda = new OleDbDataAdapter(cmd);
    oleda.Fill(ds);

    grvData.DataSource = ds.Tables[0].DefaultView;
    grvData.DataBind();
    grvData.Visible = false;

    Day();
}

private void Day()
{
    DateTime Date = DateTime.Today;
    double G;

    for (int i = 0; i < grvData.Rows.Count; i++)
    {
        if (grvData.Rows[i].Cells[22].Text == "AU")
        {
           G = (Date - Convert.ToDateTime(grvData.Rows[i].Cells[3].Text)).TotalDays;
           AUDay1.Text = Convert.ToString(G);
        }
    }
}

好像单元格3 Data有错误。我想将字符串值转换为DateTime,但它显示错误:String was not recognized as a valid DateTime.

excel数据的格式为:2014年4月1日上午1:16:32

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

 G = (Date - DateTime.ParseExact(grvData.Rows[i].Cells[3].Text).ToString().Trim(), "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture).TotalDays;

答案 1 :(得分:0)

由于您的grvData.Rows[i].Cells[3].Text4/1/2014 1:16:32 AM,因此它没有standart date and time format。这就是您Convert.ToDateTime方法抛出FormatException的原因。

您可以使用DateTime.TryParseExactDateTime.ParseExact方法来解析自定义格式化字符串。

string s = "4/1/2014 1:16:32 AM";
DateTime date;
if (DateTime.TryParseExact(s, "M/d/yyyy h:mm:ss tt",
                               CultureInfo.InvariantCulture,
                               DateTimeStyles.None, out date))
{
     Console.WriteLine(date);
}
else
{
     Console.WriteLine("Your string is not valid.");
}

输出将是;

4/1/2014 1:16:32 AM

这里有 demonstration

有关更多信息,请查看;

答案 2 :(得分:0)

你可以试试这个:

string strDate = "4/1/2014 1:16:32 AM";
DateTime datDate;
if (DateTime.TryParseExact(strDate, new string[] { "M/d/yyyy h:m:s tt" },
                        System.Globalization.CultureInfo.InvariantCulture,
                        System.Globalization.DateTimeStyles.None, out datDate))
{
    Console.WriteLine(datDate);
}

根据您的代码:

 ..................................................
    for (int i = 0; i < grvData.Rows.Count; i++)
    {
     if (grvData.Rows[i].Cells[22].Text == "AU")
     {
     string strDate = grvData.Rows[i].Cells[3].Text;
     DateTime presenetDate;           
     if (DateTime.TryParseExact(strDate, new string[] { "MM/d/yyyy h:m:s tt" },
                            System.Globalization.CultureInfo.InvariantCulture,
                            System.Globalization.DateTimeStyles.None, out datDate))
     {
       G = (Date - presenetDate).TotalDays;
           AUDay1.Text = Convert.ToString(G);
     }
     else
     {
       AUDay1.Text = "Not a Valid date";
     }
   .......................................