繁体   English   中英

Convert.ToDateTime函数发生错误,错误为“无法将字符串识别为有效的DateTime”

[英]Error on Convert.ToDateTime function, having error as “String was not recognized as a valid 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数据有错误。 我想将字符串值转换为DateTime,但它向我显示错误: String was not recognized as a valid DateTime.

Excel数据的格式如下:2014年4月1日1:16:32

我该如何解决?

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

由于您的grvData.Rows[i].Cells[3].Text4/1/2014 1:16:32 AM4/1/2014 1:16:32 AM ,因此它没有标准的日期和时间格式 这就是为什么您的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

有关更多信息,请查看;

你可以试试这个:

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";
     }
   .......................................

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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