【问题标题】:JavaScript difference between two Date()'s in months [duplicate]几个月内两个 Date() 之间的 JavaScript 差异[重复]
【发布时间】:2014-03-04 08:10:50
【问题描述】:

我正在尝试创建一个网站来告诉您(以年、月、周、小时、分钟和秒为单位)您的年龄。除了几个月和几年,我让他们所有人都在工作。一旦我得到了几个月,我将能够得到几年(希望如此),但是我很难想出一种方法来获得几个月。对于其他人来说,这很容易(一旦我有了出生日期和当前日期之间的秒数,我就可以将秒转换为分钟、小时、天等),但是几个月我需要考虑事实上,它们都是不同的长度和闰年(目前也不影响天数)。

【问题讨论】:

标签: javascript jquery html date date-difference


【解决方案1】:

希望对你有所帮助

// Set the unit values in milliseconds.
 var msecPerMinute = 1000 * 60;
 var msecPerHour = msecPerMinute * 60;
 var msecPerDay = msecPerHour * 24;

// Set a date and get the milliseconds
 var date = new Date('6/15/1990');
 var dateMsec = date.getTime();

// Set the date to January 1, at midnight, of the specified year.
   date.setMonth(0);
   date.setDate(1);
   date.setHours(0, 0, 0, 0);

// Get the difference in milliseconds.
   var interval = dateMsec - date.getTime();

// Calculate how many days the interval contains. Subtract that
// many days from the interval to determine the remainder.
   var days = Math.floor(interval / msecPerDay );
   interval = interval - (days * msecPerDay );

// Calculate the hours, minutes, and seconds.
   var hours = Math.floor(interval / msecPerHour );
   interval = interval - (hours * msecPerHour );

    var minutes = Math.floor(interval / msecPerMinute );
    interval = interval - (minutes * msecPerMinute );

    var seconds = Math.floor(interval / 1000 );

// Display the result.
   document.write(days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds.");

 //Output: 164 days, 23 hours, 0 minutes, 0 seconds.

【讨论】:

    【解决方案2】:

    您会考虑使用外部库吗?查看http://momentjs.com/

    你可以轻松地做类似的事情

    date1.diff(date2, 'months')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多