C# .NET - To check dates with current and previous days

Asked By abinav shankar on 26-Jan-12 12:39 AM


I want to check the date time in such a way that if the leave selected is vacation or Casual leave I can enable the person to apply leave from current date and future date,For instance if he is applying for casual leave he can apply from today to future dates whereas he is not allowed to take casual leave in the previous days

D Company replied to abinav shankar on 26-Jan-12 01:03 AM
Hello Friend,

you can define a method, so that every time user enters from and to date to the respective controls, your method should be able to validate and returns true and false as result. method should be look like this.

//define variables
DateTime fromd,todate,currentdate
    public bool RuleValue(DateTime _validFrom, DateTime _validTo)
fromd= _validFrom;
todate= _validTo;
//check here , take current date
//add more condition if required
if(fromd>=currentdate && todate>=currentdate)
return true;
return false;


dipa ahuja replied to abinav shankar on 26-Jan-12 02:46 AM
Two ways you  can use here:

1. Take date time picker and disable the past date
2. manually allow enter date and validate its not past date

DateTime dtLeave = DateTime.Parse(TextBox1.Text);
  if (dtLeave < DateTime.Now)
    //alert past dates not allowed

Sri K replied to abinav shankar on 26-Jan-12 07:48 AM
We have Compare method for DateTime which compares two dates. 

For example : 
int result = DateTime.Compare(ToDate,FromDate); 
If ToDate is Greater than FromDate the Compare method returns 1. 
If ToDate is Equal to FromDate the Compare method returns 0. 
If ToDate is Lesser than FromDate the Compare method returns -1.