简体   繁体   中英

C# DateTimePicker comparison issue

I want to compare the two dateTimePickers in the winforms using C#.

My comparing code is as below;

if (dtpFromDate.Value > dtpToDate.Value)
{
   MessageBox.Show("From Date is greater than To Date");
   return;
}

Below are the values of the two dateTimePickers

dtpFromDate.Value = 10/29/2016 5:10:27 PM

dtpToDate.Value = 10/29/2016 5:10:27 PM

But if the two dateTimePickers are set to be at their initial values (ie today's date) as above, the if statement got also true, but what I need is to check only if the dates are greater (FromDate>ToDate). Am I doing something wrong?

If you do not care the time, do that:

if (dtpFromDate.Value.Date > dtpToDate.Value.Date)
{
   MessageBox.Show("From Date is greater than To Date");
   return;
}

To be explicit here, the data type of dtpFromDate.Value is of DateTime . I always prefer to use DateTime.Tick property for DateTime comparisons, since it is an integral type, so the comparison is obvious to the reader and also fast.

I believe when the two different DateTimePicker controls are created, they differ in their values by less than a second, causing the issue. If your intention is to simply compare the DateTime with a least count of second , then you can do this

if ((dtpFromDate.Value.Ticks / TimeSpan.TicksPerSecond) > 
     (dtpToDate.Value.Ticks / TimeSpan.TicksPerSecond))
{
   MessageBox.Show("From Date is greater than To Date");
   return;
}

The DateTime object has a least count of a Tick . You can read up on DateTime.Ticks and TimeSpan on MSDN

A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond, or 10 million ticks in a second.

I had two date time pickers on the same windows form. Even though I was making a comparison of dtpStartDate.Value.Date and dtpEndDate.Value.Date, the check for the end date being earlier than the start date was still coming up wrong when it appeared that the two date time picker values were the same. It wasn't until I compared the values down to the millisecond like dtpEndDate.Value.ToString("MM/dd/yyyy HH:mm:ss.fff") and dtpStartDate.Value.ToString("MM/dd/yyyy HH:mm:ss.fff") that I saw the difference.

In my case I wanted to only compare month, day and year. What I had to do to make a proper comparison was use

if (dtpStartDate.Value.Date.Date > dtpEndDate.Value.Date.Date)
        {
            // Start Date cannot be later than the End Date
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM