如何从字符串日期将值设置为Datetime对象

时间:2013-11-07 12:16:55

标签: c# datetime

我已经编写了一些代码来从字符串datagridview列获取日期并将其设置为datetime对象,但它显示错误

foreach (DataGridViewRow r in dataGridView1.Rows)
{
    string day = r.Cells["l_date_from"].Value.ToString().Substring(0,2);
    string month = r.Cells["l_date_from"].Value.ToString().Substring(3,2);
    string year = r.Cells["l_date_from"].Value.ToString().Substring(6,4);

    string mydate_From = month + "/" + day + "/" + year;

    day = r.Cells["l_date_To"].Value.ToString().Substring(0, 2);
    month = r.Cells["l_date_To"].Value.ToString().Substring(3, 2);
    year = r.Cells["l_date_To"].Value.ToString().Substring(6, 4);
    string mydate_To = month + "/" + day + "/" + year;

    cmd.CommandText = "insert into " + table_Name + " (entry_no,invoice_number,invoice_date,sid,h_sr_no,hid,h_name,h_location,h_size1,h_size2,h_size_sqf,hRate,number_of_months,hTotal,from_date,to_date,hTotalAmount,advance,balance,e_date,e_uid,e_fid,transaction_code) values (" + txtEntryNo.Text + "," + txtInvoiceNo.Text + ",'" + txtDate.Value.ToString("MM/dd/yyyy") + "'," + Supplier_number + "," + r.Cells["l_sr"].Value.ToString() + "," + r.Cells["l_hid"].Value.ToString() + ",'" + r.Cells["l_h_name"].Value.ToString() + "','" + r.Cells["l_hLocation"].Value.ToString() + "'," + r.Cells["l_hsize1"].Value.ToString() + "," + r.Cells["l_hsize2"].Value.ToString() + "," + r.Cells["l_hsizesqf"].Value.ToString() + "," + r.Cells["l_rate"].Value.ToString() + "," + r.Cells["l_nom"].Value.ToString() + "," + r.Cells["l_total"].Value.ToString() + ",'" + mydate_From + "','" + mydate_To + "'," + txtTotal.Text + "," + txtAdvance.Text + "," + txtBalance.Text + ",'" + DateTime.Now.ToString("MM/dd/yyyy") + "'," + Global_.Functions_.Entry_UID_ + "," + Global_.Functions_.Entry_FID_ + ",'" + tra_code + "')";
    cmd.ExecuteNonQuery();
}

datagridview列返回日期值如(“7/11/2013”​​),这个值我想设置为Datetime Object。

2 个答案:

答案 0 :(得分:1)

除非你在某个地方使用字符串日期,否则你可以稍微改变你的逻辑。

而不是这样做

string mydate_From = month + "/" + day + "/" + year;

创建DateTime实例direclty

var mydate_From = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day));

修改

实际上,我认为这可以解决问题

var mydate_From = DateTime.ParseExact(
     r.Cells["l_date_from"].Value.ToString(), 
     "dd/MM/yyyy", 
     CultureInfo.InvariantCulture);

var mydate_To = DateTime.ParseExact(
     r.Cells["l_date_To"].Value.ToString(), 
     "dd/MM/yyyy", 
     CultureInfo.InvariantCulture);

答案 1 :(得分:0)

DateTimeFormatInfo dateformat= new DateTimeFormatInfo();
dateformat.ShortDatePattern = "dd/MM/yyyy";
dateformat.DateSeparator = "/";
DateTime objDate = Convert.ToDateTime(strDate, dateformat);