Nathan
Nathan

Reputation: 1347

dateTimePicker incorrect date

I'm using dateTimePickers so the user can specify a to and from date for something in my program. Obviously the "From" value should be before or equal to the "To" Value, so I've added this:

    public CustomReportDialog()
    {
        InitializeComponent();
        dateTimePicker1.MaxDate = DateTime.Now; //From Field   
        dateTimePicker2.MaxDate = DateTime.Now; //To Field
    }



    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(dateTimePicker1.Value.ToString());
        MessageBox.Show(dateTimePicker2.Value.ToString());
        if (dateTimePicker2.Value < dateTimePicker1.Value)
        {
            MessageBox.Show("Error!");
        }

If I just open up the form and click the button though, it shows the error message, even though the messageboxes prove the two datetimes are the exact same. If I change one of the dates though, and then change it back so they're equal, no errors shows... Anyone know why? Thanks!

Upvotes: 0

Views: 731

Answers (1)

Jesse Dietrichson
Jesse Dietrichson

Reputation: 21

So whats happening is when the program starts, the values of the datetimepickers are actually different by a few milliseconds! Try setting both value and maxdate properties.

  DateTime currentTime = DateTime.Now;
  dateTimePicker1.Value = currentTime;
  dateTimePicker2.Value = currentTime;
  dateTimePicker1.MaxDate = currentTime; //From Field   
  dateTimePicker2.MaxDate = currentTime; //To Field

Upvotes: 2

Related Questions