www.webdeveloper.com
Results 1 to 2 of 2

Thread: Subtract 2 dates and return Month

  1. #1
    Join Date
    Jul 2012
    Posts
    1

    Subtract 2 dates and return Month

    I have been trying to find this information but have been unable to. I have an HTML form that has 2 fields (todays_date, mat_date) that have been formatted to accept a date in this format (MM/DD/YY). I need to get the difference between these two dates (mat_date - todays_date) returned in the number of months (1st day of the month is the same as the last day) and this needs to be calculated/returned in once the total_mths field is tabed into or clicked on. Any help is appreciated.

    Thanks!

  2. #2
    Join Date
    Mar 2012
    Location
    Saint-Petersburg, Russia
    Posts
    97
    You just need to create two Date objects by fields' values, then you can easily find difference in milliseconds and then convert it to minutes, hours or days simply by division:
    Code:
    var diff = new Date(field1.value).getTime() - new Date(field2.value).getTime();
    // or the same
    var diff = Date.parse(field1.value) - Date.parse(field2.value);
    var days = diff / 1000 / 60 / 60 / 24;
    However if you want to find out difference in months (month is not determined period of time) you need to decide what you mean by month.

    For some applications you prefer to think of month as of 30.44 days (financial, statistics etc) or even about 21.7 working days.

    In other cases, when you want to count the number of real months, your task is even simpler - get years and months from both dates and subtract them:
    Code:
    var d1 = new Date(field1.value);
    var d2 = new Date(field2.value);
    // d1.setTime(d1.getTime() + 15.22 * 24 * 60 * 60 * 1000);
    var diff = d1.getYear() * 12 + d1 .getMonth() - d2.getYear() * 12 - d2.getMonth();
    The line which is commented allows you to add compensation (about 15 days) to larger date so that error of result is -0.5...+0.5 instead of -1..0.

    Here is one of descriptions of Date object in javascript:
    http://www.w3schools.com/jsref/jsref_obj_date.asp

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles