简体   繁体   English

如何计算JavaScript中两个日期之间的年,月和天的差异?

[英]How can I calculate the difference in years, months and days between two dates in Javascript?

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 示例:从:2013年10月1日到:2013年11月15日

Output: 1 Month and 15 Days 产出:1个月15天

I've tried momentjs but it display the whole months and days, like 1 Month, 45 Days. 我尝试了momentjs,但是它显示了整个月和几天,例如1个月,45天。 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 "

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. 您必须进行一些估算(一个月是31天,一年是365天,依此类推),并且在进行过程中必须从diff减去已经使用的数字。

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 之间的区别1/1/20007/16/2001 ,通过该代码: 1 years 6 months 16 days

Got the answer here: Convert a number (of days) to days, months and years with jQuery 在这里得到答案: 使用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JavaScript计算年,月,日,小时,分钟的两个日期之间的差 - JavaScript calculate difference between two dates, in Years, Months, Days, Hours, Minutes JavaScript 中两个日期之间的年、月、日差 - Difference between two dates in years, months, days in JavaScript 如何在JavaScript中计算两个日期之间的年和月? - How to calculate years and months between two dates in Javascript? 我可以通过momentjs得出年份和月份中两个日期之间的差额吗? - Can I get the difference between two dates in years and months with momentjs? 计算使用Bootstrap Datepicker设置的两个日期之间的差异,以年,月和日为单位 - Calculate the difference between two dates set using Bootstrap Datepicker in terms of Years, Months and Days 如何计算两个日期之间的年数? - How can I calculate the number of years between two dates? 如何获取JavaScript中两个日期之间的差值天? - How do I get the difference days between two Dates in JavaScript? 如何使用moment.js获得年、月和日的2个日期之间的差异 - How to get difference between 2 Dates in Years, Months and days using moment.js 如何比较两个日期并根据差异返回年份或天? - How can I compare two dates and return years or days depending on difference? 计算两个日期之间的天数差 - Calculate the difference between two dates in number of days
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM