dateTimePicker1.Value < dateTimePicker2.Value = true when values are identical on runtime

1k Views Asked by At

I have dateTimePicker1 and dateTimePicker2 controls loading on Form1. They both have the same date and time on load.

        dateTimePicker1.Format = DateTimePickerFormat.Custom;
        dateTimePicker1.CustomFormat = "yyyy-MM-dd hh:mm:ss";
        dateTimePicker2.Format = DateTimePickerFormat.Custom;
        dateTimePicker2.CustomFormat = "yyyy-MM-dd hh:mm:ss" 

When I check if they have different values using

if (dateTimePicker1.Value < dateTimePicker2.Value) {
    Console.WriteLine(dateTimePicker1.Value + " is earlier than " + dateTimePicker2.Value);
}

the statement returns true and writes to the console. This is not what I would expect. I would expect this to return false.

If I increase each control's value by 1 second, causing them to still match, the statement returns false as expected and nothing is written to the console.

Why does the less than evaluation return true on load when both values are identical?

2

There are 2 best solutions below

0
On

Do not know how you are loading the values. But, depending on what precision you are looking for (eg. in hours, minutes or second) you can subtract the two values and compare. Example: If you need precision in seconds then you can do something similar to below:

        dateTimePicker1.Value = DateTime.Now;
        dateTimePicker2.Value = DateTime.Now.AddMilliseconds(999);
        var timeSpan1 = dateTimePicker1.Value - dateTimePicker2.Value;
        if (Math.Abs(timeSpan1.TotalSeconds) > 1) {
            MessageBox.Show(dateTimePicker1.Value + " is not same as " + dateTimePicker2.Value);
        } else {
            MessageBox.Show(dateTimePicker1.Value + " is same as " + dateTimePicker2.Value);
        }
0
On

The answer is given by setting the two values equal to each other on load. This is because the controls load at different times. They are not really equal.

    private void Form1_Load(object sender, EventArgs e)
    {
        dateTimePicker2.Value = dateTimePicker1.Value;
    }

I'm not sure how to give credit here, it belongs to two commenters.