1. 程式人生 > >c#檢查開始日期是否大於結束日期

c#檢查開始日期是否大於結束日期

winfrom:

private void dteStartDate_Validating(object sender, CancelEventArgs e)
 {
     if (!CheckStartDateEndDate(true))
     {
         XtraMessageBox.Show("起始日期不能大於結束日期");
         dteStartDate.Focus();
         e.Cancel = true;
     }
 }
 
 private void dteEndDate_Validating(object sender, CancelEventArgs e)
 {
     if (!CheckStartDateEndDate(false))
     {
         XtraMessageBox.Show("結束日期不能小於起始日期");
         dteEndDate.Focus();
         e.Cancel = true;
     }
 }

private bool CheckStartDateEndDate(bool bLeaveFromStartDate)
 {
     if (!(string.IsNullOrEmpty(dteStartDate.Text) || string.IsNullOrEmpty(dteEndDate.Text)))
     {
         if (Convert.ToDateTime(dteStartDate.Text) > Convert.ToDateTime(dteEndDate.Text))
         {
             if (bLeaveFromStartDate)
             {
                 return false;
             }
             else
             {
                 return false;
             }
         }
     }
     return true;
 }

web:

if (txtStartDate.Value==null || !PageValidate.IsDateTime(txtStartDate.Value.ToString()))
 
 strErr+="請輸入正確的開始日期!\\n";   
 
         if (txtEndDate.Value == null || !PageValidate.IsDateTime(txtEndDate.Value.ToString()))
 
             strErr += "請輸入正確www.2cto.com的結束日期!\\n"; 
 
 
         if(Convert.ToDateTime(txtStartDate.Value.ToString()).CompareTo(Convert.ToDateTime(txtEndDate.Value.ToString()))>0)
         {
             strErr += "開始時間不能大於結束時間!\\n";   
         }

/// <summary>
     /// 日期格式字串判斷
     /// </summary>
     /// <param name="str"></param>
     /// <returns></returns>
     public static bool IsDateTime(string str)
     {
         try
         {
             if (!string.IsNullOrEmpty(str))
             {
                 DateTime.Parse(str);
                 return true;
             }
             else
             {
                 return false;
             }
         }
         catch
         {
             return false;
         }
     } 

轉載自keenweiwei部落格