簡體   English   中英

如何在dataGrid中將日期值與當前日期進行比較?

[英]How to compare date values In dataGrid with current date?

我試過了

protected void gridCustomer_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
      DateTime olddate = Convert.ToDateTime(e.Row.Cells[9].Text);
      // Error : String was not recognized as a valid DateTime./ 'DateTime today = DateTime.Now;'
      if (olddate > today)
      {
          Label status = (Label) e.Row.FindControl("lblStatus");
          status.Text = "AutoHold";
      }
   }
}

如果不提供任何IFormatProvider作為第二個參數,則Convert.ToDateTime方法 默認使用CurrentCulture設置。

這意味着,您的CurrentCulture沒有yyyy-MM-dd作為標准日期和時間格式。

在這種情況下,您可以使用DateTime.TryParseExactDateTime.ParseExact方法指定您的字符串格式;

DateTime olddate;
if(DateTime.TryParseExact(e.Row.Cells[9].Text, "yyyy-MM-dd", 
                          CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out olddate))
{
    // Your olddate will be 28/03/2015 00:00:00
}

但是在舊日期得到'1/1/0001',就像在我的網格單元格中,我在上面提到的代碼上面有'4/1/2015'。

顯然,您的4/1/2015yyyy-MM-dd格式不匹配,這就是為什么您的olddate將是DateTime的默認值,即DateTime.MinValue1/1/0001)

如果您的字符串可以是多種格式,則DateTime.TryParseExact具有將格式作為字符串數組的重載 有了它,您可以指定字符串的所有可能格式。

例如;

string s = "4/1/2015";
DateTime dt;
var formats = new string[]{"yyyy-MM-dd", "M/d/yyyy"};
if(DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    // Your dt will be 01/04/2015 00:00:00
}

采用:

CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "2015-03-28";
format = "yyyy-MM-dd";
try {
  result = DateTime.ParseExact(dateString, format, provider);
  Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
  Console.WriteLine("{0} is not in the correct format.", dateString);
}

MSDN

使用DateTime.ParseExact

string res = "2012-07-08";
DateTime d = DateTime.ParseExact(res, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("MM/dd/yyyy")); // can set any format

在代碼中替換此行

DateTime olddate = DateTime.ParseExact(e.Row.Cells[9].Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);

如果當前區域性和日期時間字符串的格式存在差異,則Convert.ToDateTime將拋出異常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM