2017-08-03 3 views
0

ラベルである日付フィールドを持つグリッドビューがあります。 その日が現在の日付から過去3ヶ月かどうかを調べたいと思います。 私はこれをDataBoundイベントで実行しています。ラベル日付が過去3ヶ月であるかどうかを調べる方法

protected void gvcmi_DataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     Label LastVisitLbl = (Label)e.Row.Cells[7].FindControl("lblStatusv"); 
     If (LastVisitLbl /*not sure what to put here*/) 
     { 
      //Do something 
     } 
    } 
} 

私は第二の場合に置くべきかに立ち往生しています: はここに私のスニペットです。

+0

ラベルのテキストは日付を表しますか?はいの場合、どの形式ですか? – Ben

答えて

2

あなたはDateTime.TryParseを使用してDateTime変数にラベルのテキストをキャストしてDateTime.Nowマイナス3ヶ月と比較することができます:

DateTime date; 
if (DateTime.TryParse(LastVisitLbl.Text, out date)) 
{ 
    if (date < DateTime.Now.AddMonths(-3)) 
    { 
      // Do Something 
    } 
} 
else 
    // Error - the label's format is not a correct DateTime 
+0

おそらくあなたは 'DateTime.TryParse'で日付を変換するべきです。したがって、例外はスローされません。 – DogeAmazed

+1

'if(DateTime.TryParse(LastVisitLbl.Text、out date))' :) – DogeAmazed

2

あなたはDateTime.ParseExactまたはDateTime.TryParseExactを使用することができます。あなたがそれらのラベルをレンダリングしているとして、あなたはあなただけdd/MM/yyyyあなたは日付がレンダリングされた知っているフォーマットであるParseExact

protected void gvcmi_DataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      Label LastVisitLbl = (Label)e.Row.Cells[7].FindControl("lblStatusv"); 
      If (DateTime.ParseExact(LastVisitLbl.Text, "dd/MM/yyyy", Thread.CurrentThread.CurrentUICulture.DateTimeFormat) >= DateTime.Today.AddMonths(-3) 
      { 
       //Do Something 
      } 
     } 
} 

を使用することができますので、日付が正しい形式であることを信頼することができます。

関連する問題