-4

Possible Duplicate:
How do I get the difference between two Dates in JavaScript?

I have a html form which contains 3 fields:

  1. from_date
  2. to_date
  3. no_ofdays

I want to calculate the difference between from_date and to_date and the difference will be shown in no_ofdays field. My requirement is the to_date must not be less than from_date. And if the condition fails it should not calculate the difference and also the to_date should remain null.

I want to do it using JavaScript.

Community
  • 1
  • 1
user1369099
  • 21
  • 1
  • 5
  • @user1369099 please update the question with the code. Anyway, I think the duplicate questions posted might have answered your question. – OnesimusUnbound May 02 '12 at 04:30

1 Answers1

0

Briefly, this is how you do it:

  1. Parse the values of the fields into Date objects. Datejs can help you do this.
  2. Date objects support the < and - operators, letting you do what you want.
  3. When you subtract two Date objects, the result is the difference in milliseconds.
  4. If you divide the difference in milliseconds by the number of milliseconds in a day, then you get how many days there are between the dates.
  5. You can then put the result in the result field.
icktoofay
  • 126,289
  • 21
  • 250
  • 231