几个月内两个Date()的JavaScript差异

时间:2014-02-07 03:41:03

标签: javascript jquery html date date-difference

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

2 个答案:

答案 0 :(得分:0)

希望这可以帮助你

// 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.

答案 1 :(得分:0)

你会考虑一个外部图书馆吗?查看http://momentjs.com/

您可以轻松地执行类似

的操作
date1.diff(date2, 'months')