Thursday, January 24, 2013

Compare two date in CSharp (C#)

Some times you may have a situation to compare two dates for the date validation. You can do this easily using the DateTime.Compare method.
public bool ValidateDate(string from,string to)  
{  
     bool isValid = false;  
     if (from != string.Empty && to != string.Empty)  
     {  
          if (DateTime.Compare(Convert.ToDateTime(txt_From.Text), Convert.ToDateTime(txt_To.Text)) == 1)  
          {  
               isValid = false;  
          }  
          else  
          {  
               isValid = true;  
          } 
 
          if (DateTime.Compare(Convert.ToDateTime(to), DateTime.Now) > 0)  
          {  
          isValid = false;  
          }  
     } 
 
     return isValid;  
}