Philo
Philo

Reputation: 1989

C# compare two DateTimes

I have two dates:

DateTime date_of_submission = Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy"));
DateTime _effective_date = Convert.ToDateTime(TextBox32.Text);

Now the effective date cannot be more than 90 days in the future from date of submission.

How can I do this comparison?

One method that comes to mind is a naive convert date times to strings and then compare dd, mm, yyyy and see if both dates are within 90 days of each other. But I believe there has to be a better solution than that.

Upvotes: 13

Views: 77806

Answers (6)

Abdur Rahim
Abdur Rahim

Reputation: 4021

Though there are several effective solution, It could be one for future searchers

DateTime date_of_submission = Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy"));
DateTime _effective_date = Convert.ToDateTime(TextBox32.Text);

DateTime lastPossibleEffectiveDate = _effective_date.AddDays(90);

int result = DateTime.Compare(_effective_date,lastPossibleEffectiveDate);
if (result <= 0)
    Console.WriteLine("Valid Date");
else if (result > 0 )
    Console.WriteLine("Not Valid effective date");

Upvotes: 0

Chandan Kumar
Chandan Kumar

Reputation: 4638

This is a sample to compare datetime. you can change according to your requirement

 DateTime dtFromDate = DateTime.ParseExact(TextBoxFromDate.Text, "dd/MM/yyyy",
                                                   CultureInfo.InvariantCulture);
 DateTime dtToDate = DateTime.ParseExact(TextBoxToDate.Text, "dd/MM/yyyy",
                                                   CultureInfo.InvariantCulture);
 TimeSpan difference = dtFromDate - dtToDate;
 double days = difference.TotalDays;

 if (days > 0)
 {
   DivFormError.InnerText = "“From Date” cannot be greater than “To Date”";
 }

Upvotes: 0

terryt
terryt

Reputation: 561

Something like...

        TimeSpan difference = _effective_date - date_of_submission;
        double days = difference.TotalDays;

        if (days > 0 && days <= 90)
        {
            //valid
        }

Upvotes: 3

Max
Max

Reputation: 4077

You can compare two datetime values with each other as you normally compare.

So, you can do the following :-

if(date_of_effective_date.CompareTo(date_of_submission_date.AddDays(90)) <= 0)
{
 //Correct
}

Upvotes: 1

Christian Hayter
Christian Hayter

Reputation: 31071

var days = (_effective_date - date_of_submission).Days;

Upvotes: 4

Sean
Sean

Reputation: 62472

You can subtract two dates, and get a TimeSpan :

TimeSpan difference = _effective_date - date_of_submission;
if(difference.TotalDays > 90)
{
  // Bingo!
}

Upvotes: 26

Related Questions