IN y application, i have a date shown in textbox control which is extract from database(previously saved in MM/dd/yyyy format).Now i have to compare that date with another date that user inputs from datetimepicker control(custom format MM/dd/yyyy).Now i have to compare this two date and throw some message accordingly after comparision.
my code is like below, which gives error as "String was not
recognized as a valid DateTime."

        string textdate1 = textbox1.text;
        string textdate2 = datetimepicker1.text;
        System.DateTime d1 = System.DateTime.Parse(textdate1);
        System.DateTime d2 = System.DateTime.Parse(textdate2);

        if (System.DateTime.Compare(d1, d2) < 0)
        {
            MessageBox.Show("date 2 is later then date 1");
        }

can anyone help me for this,its urgent for me.........

Recommended Answers

All 3 Replies

Please use code tags when posting on daniweb.

You can compare dates using comparison operators:

private void button4_Click(object sender, EventArgs e)
    {
      DateTime dt1 = DateTime.Now;
      DateTime dt2 = DateTime.Now.AddDays(-1);
      if (dt1 > dt2)
      {
        MessageBox.Show("greater");
      }
    }

If the date is in mm/dd/yyyy then what is your locale settings? Are they american english or something else? This can change the behavior of parsing values. Also -- Which line of code is failing? The textdate1 or textdate2. There should also be a property off of DateTime pickers called .Date where you can get the DateTime value instead of parsing the string value.

Thanks for quick reply & suggestion. well my setting is US English .my problem is actually with the date in string format. which throws error. my question is to compare the date of datetimepicer value & the one from database(which is datetime field and shown as string in front end.) i haven't get correct solution , but its really urgent for me...

Which line of code is failing? Also post a sample of the string you are trying to convert to a DateTime . Make sure you use the debugger and evaluate the .Text property and post that here, not copying and pasting the value from the text box.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.