最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I calculate the difference in years, months and days between two dates in Javascript? - Stack Overflow

programmeradmin0浏览0评论

How can I calculate the difference between two days telling me the remaining years remaining months and remaining days?

Example: From: Oct 1 2013 To: Nov 15 2013

Output: 1 Month and 15 Days

I've tried momentjs but it display the whole months and days, like 1 Month, 45 Days. I also tried this function but it displays the same thing:

var diff = Math.floor(end_date.getTime() - start_date.getTime());
var day = 1000* 60 * 60 * 24;
var days = Math.floor(diff/day);
var months = Math.floor(days/31);
var years = Math.floor(months/12);

var message = days + " days " 
message += months + " motnhs "

How can I calculate the difference between two days telling me the remaining years remaining months and remaining days?

Example: From: Oct 1 2013 To: Nov 15 2013

Output: 1 Month and 15 Days

I've tried momentjs but it display the whole months and days, like 1 Month, 45 Days. I also tried this function but it displays the same thing:

var diff = Math.floor(end_date.getTime() - start_date.getTime());
var day = 1000* 60 * 60 * 24;
var days = Math.floor(diff/day);
var months = Math.floor(days/31);
var years = Math.floor(months/12);

var message = days + " days " 
message += months + " motnhs "
Share Improve this question asked Nov 27, 2013 at 16:49 joseagaleanocjoseagaleanoc 6152 gold badges8 silver badges20 bronze badges 5
  • possible duplicate of How do I get the difference between two Dates in JavaScript? – Brian S Commented Nov 27, 2013 at 16:52
  • Seems like it does what you want? What is the output you're expecting? – Nick Commented Nov 27, 2013 at 16:58
  • Here is another interesting answer which may help - stackoverflow./questions/8942895/… – Mark Walters Commented Nov 27, 2013 at 17:02
  • Its not what I'm expecting since I dont want to know the full days and months in between but the months in between and the remaining days... – joseagaleanoc Commented Nov 28, 2013 at 20:08
  • @BrianS Its not a duplicate since the question you mention returns the days, hours and minutes...those are all standard but month change – joseagaleanoc Commented Nov 28, 2013 at 20:11
Add a ment  | 

4 Answers 4

Reset to default 2

Days seems to be the trickiest calculation, otherwise it's pretty straight-forward. Subtract the current milliseconds from the target milliseconds to get the duration in milliseconds. Then for each value but days, take the floor of the duration divided by the number of milliseconds in either a year, month, hour, minute or second. This gives you the number or years, months, hours, minutes or seconds in the duration. Finally, take the modulus of each of the values.

For days, subtract the number of years and months in milliseconds from the duration to get the remaining milliseconds, then take the floor of the remaining milliseconds divided by the number of milliseconds in a day.

function countdown(targetDate) {
  var nowMillis = new Date().getTime();
  var targetMillis = targetDate.getTime();
  var duration = targetMillis - nowMillis;
  var years = Math.floor(duration / 3.154e+10);
  var durationMinusYears = duration - (years * 3.154e+10);
  var months = Math.floor(duration / 2.628e+9) % 12;
  var durationMinusMonths = durationMinusYears - (months * 2.628e+9);
  var days = Math.floor(durationMinusMonths / 8.64e+7);
  var hours = Math.floor(duration / 3.6e+6 ) % 24;
  var mins = Math.floor(duration / 60000 ) % 60;
  var secs = Math.floor(duration / 1000 ) % 60;

  return [ years, months, days, hours, mins, secs ];
}

console.log('Count down until IE11 is no longer supported => ' + countdown(new Date(2020, 9, 13, 0, 0)));

You have to do some estimating (a month is 31 days, a year is 365 days, etc) AND you have to subtract the number you've already used from diff as you go along.

var diff = Math.floor(end_date.getTime() - start_date.getTime());
var 
    lengthOfDayInSeconds = 1000* 60 * 60 * 24,
    lengthOfMonthInSeconds = lengthOfDayInSeconds*31,
    lengthOfYearInSeconds = lengthOfDayInSeconds*365;

var yearsBetween = Math.floor(diff/lengthOfYearInSeconds);
diff -= yearsBetween*lengthOfYearInSeconds;

var monthsBetween = Math.floor(diff/lengthOfMonthInSeconds);
diff -= monthsBetween*lengthOfMonthInSeconds;

var daysBetween = Math.floor(diff/lengthOfDayInSeconds);

message = yearsBetween + ' years '+ monthsBetween + ' months ' + daysBetween + ' days';

The difference between 1/1/2000 and 7/16/2001 is, by this code: 1 years 6 months 16 days

Got the answer here: Convert a number (of days) to days, months and years with jQuery

With this function:

function humanise(total_days)
{
    //var total_days = 1001;
    var date_current = new Date();
    var utime_target = date_current.getTime() + total_days*86400*1000;
    var date_target = new Date(utime_target);

    var diff_year  = parseInt(date_target.getUTCFullYear() - date_current.getUTCFullYear());
    var diff_month = parseInt(date_target.getUTCMonth() - date_current.getUTCMonth());
    var diff_day   = parseInt(date_target.getUTCDate() - date_current.getUTCDate());

    var days_in_month = [31, (date_target.getUTCFullYear()%4?29:28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    var date_string = "";
    while(true)
    {
        date_string = "";
        date_string += (diff_year>0?diff_year + "Y":"");

        if(diff_month<0){diff_year -= 1; diff_month += 12; continue;}
        date_string += (diff_month>0?diff_month + "M":"");

        if(diff_day<0){diff_month -= 1; diff_day += days_in_month[((11+date_target.getUTCMonth())%12)]; continue;}
        date_string += (diff_day>0?diff_day + "D":"");
        break;
    }
    return date_string;
}

I'm using this to get the value. modification from this link

function get_number_of_days(firstDate, secondDate) {
   var diff_year  = parseInt(secondDate.getFullYear() - firstDate.getFullYear());
   var diff_month = parseInt(secondDate.getMonth() - firstDate.getMonth());
   var diff_day   = parseInt(secondDate.getDate() - firstDate.getDate());

   var hash_date = {};

   while(true) {
     hash_date = {};
     hash_date["y"] = diff_year;

     if(diff_month < 0) {
       diff_year -= 1; 
       diff_month += 12; 
       continue;
     }
     hash_date["m"] = diff_month;

     if(diff_day < 0) {
       diff_month -= 1; 
       diff_day += get_month_length(secondDate.getFullYear(), secondDate.getMonth());
       continue;
     }
     hash_date["d"] = diff_day;
     break;
   }

   return hash_date;
}

function get_month_length(year, month) {
    var hour = 1000 * 60 * 60;
    var day = hour * 24;
    var this_month = new Date(year, month, 1);
    var next_month = new Date(year, month + 1, 1);
    var length = Math.ceil((next_month.getTime() - this_month.getTime() - hour)/day);

   return length;
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论