[英]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.TryParseExact
或DateTime.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/2015
與yyyy-MM-dd
格式不匹配,這就是為什么您的olddate
將是DateTime
的默認值,即DateTime.MinValue
( 1/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);
}
使用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.