如何计算javascript中的日期差异

时间:2022-08-25 17:48:20

I want to calculate date difference in days, hours, minutes, seconds, milliseconds, nanoseconds, how can I do it? Please suggest.

我想计算日期,小时,分钟,秒,毫秒,纳秒的日期差异,我该怎么办?请建议。

14 个解决方案

#1


150  

Assuming you have two Date objects, you can just subtract them to get the difference in milliseconds:

假设你有两个Date对象,你可以减去它们以获得毫秒级的差异:

var difference = date2 - date1;

From there, you can use simple arithmetic to derive the other values.

从那里,您可以使用简单的算法来导出其他值。

#2


56  

var DateDiff = {

    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000));
    },

    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000*7));
    },

    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();

        return (d2M+12*d2Y)-(d1M+12*d1Y);
    },

    inYears: function(d1, d2) {
        return d2.getFullYear()-d1.getFullYear();
    }
}

var dString = "May, 20, 1984";

var d1 = new Date(dString);
var d2 = new Date();

document.write("<br />Number of <b>days</b> since "+dString+": "+DateDiff.inDays(d1, d2));
document.write("<br />Number of <b>weeks</b> since "+dString+": "+DateDiff.inWeeks(d1, d2));
document.write("<br />Number of <b>months</b> since "+dString+": "+DateDiff.inMonths(d1, d2));
document.write("<br />Number of <b>years</b> since "+dString+": "+DateDiff.inYears(d1, d2));

Code sample taken from here.

代码示例取自此处。

#3


26  

Another solution is convert difference to a new Date object and get that date's year(diff from 1970), month, day etc.

另一个解决方案是将差异转换为新的Date对象并获取该日期的年份(1970年的差异),月,日等。

var date1 = new Date(2010, 6, 17);
var date2 = new Date(2013, 12, 18);
var diff = new Date(date2.getTime() - date1.getTime());
// diff is: Thu Jul 05 1973 04:00:00 GMT+0300 (EEST)

console.log(diff.getUTCFullYear() - 1970); // Gives difference as year
// 3

console.log(diff.getUTCMonth()); // Gives month count of difference
// 6

console.log(diff.getUTCDate() - 1); // Gives day count of difference
// 4

So difference is like "3 years and 6 months and 4 days". If you want to take difference in a human readable style, that can help you.

所以差异就像“3年6个月4天”。如果你想在人类可读的风格上有所不同,那可以帮助你。

#4


19  

Expressions like "difference in days" are never as simple as they seem. If you have the following dates:

像“天差”这样的表达从来就不像看起来那么简单。如果您有以下日期:

d1: 2011-10-15 23:59:00
d1: 2011-10-16 00:01:00

the difference in time is 2 minutes, should the "difference in days" be 1 or 0? Similar issues arise for any expression of the difference in months, years or whatever since years, months and days are of different lengths and different times (e.g. the day that daylight saving starts is 1 hour shorter than usual and two hours shorter than the day that it ends).

时间的差异是2分钟,“天数差异”应该是1还是0?类似的问题出现在几个月,几年或其他任何表达的差异,因为年,月和日具有不同的长度和不同的时间(例如,夏令时开始的日子比通常短1小时,比那天短2小时)它结束了)。

Here is a function for a difference in days that ignores the time, i.e. for the above dates it returns 1.

这是一个忽略时间的天数差异的函数,即上面的日期它返回1。

/*
   Get the number of days between two dates - not inclusive.

   "between" does not include the start date, so days
   between Thursday and Friday is one, Thursday to Saturday
   is two, and so on. Between Friday and the following Friday is 7.

   e.g. getDaysBetweenDates( 22-Jul-2011, 29-jul-2011) => 7.

   If want inclusive dates (e.g. leave from 1/1/2011 to 30/1/2011),
   use date prior to start date (i.e. 31/12/2010 to 30/1/2011).

   Only calculates whole days.

   Assumes d0 <= d1
*/
function getDaysBetweenDates(d0, d1) {

  var msPerDay = 8.64e7;

  // Copy dates so don't mess them up
  var x0 = new Date(d0);
  var x1 = new Date(d1);

  // Set to noon - avoid DST errors
  x0.setHours(12,0,0);
  x1.setHours(12,0,0);

  // Round to remove daylight saving errors
  return Math.round( (x1 - x0) / msPerDay );
}

This can be more concise:

这可以更简洁:

/*  Return number of days between d0 and d1.
**  Returns positive if d0 < d1, otherwise negative.
**
**  e.g. between 2000-02-28 and 2001-02-28 there are 366 days
**       between 2015-12-28 and 2015-12-29 there is 1 day
**       between 2015-12-28 23:59:59 and 2015-12-29 00:00:01 there is 1 day
**       between 2015-12-28 00:00:01 and 2015-12-28 23:59:59 there are 0 days
**        
**  @param {Date} d0  - start date
**  @param {Date} d1  - end date
**  @returns {number} - whole number of days between d0 and d1
**
*/
function daysDifference(d0, d1) {
  var diff = new Date(+d1).setHours(12) - new Date(+d0).setHours(12);
  return Math.round(diff/8.64e7);
}

// Simple formatter
function formatDate(date){
  return [date.getFullYear(),('0'+(date.getMonth()+1)).slice(-2),('0'+date.getDate()).slice(-2)].join('-');
}

// Examples
[[new Date(2000,1,28), new Date(2001,1,28)],  // Leap year
 [new Date(2001,1,28), new Date(2002,1,28)],  // Not leap year
 [new Date(2017,0,1),  new Date(2017,1,1)] 
].forEach(function(dates) {
  document.write('From ' + formatDate(dates[0]) + ' to ' + formatDate(dates[1]) +
                 ' is ' + daysDifference(dates[0],dates[1]) + ' days<br>');
});

#5


16  

<html lang="en">
<head>
<script>
function getDateDiff(time1, time2) {
  var str1= time1.split('/');
  var str2= time2.split('/');

  //                yyyy   , mm       , dd
  var t1 = new Date(str1[2], str1[0]-1, str1[1]);
  var t2 = new Date(str2[2], str2[0]-1, str2[1]);

  var diffMS = t1 - t2;    
  console.log(diffMS + ' ms');

  var diffS = diffMS / 1000;    
  console.log(diffS + ' ');

  var diffM = diffS / 60;
  console.log(diffM + ' minutes');

  var diffH = diffM / 60;
  console.log(diffH + ' hours');

  var diffD = diffH / 24;
  console.log(diffD + ' days');
  alert(diffD);
}

//alert(getDateDiff('10/18/2013','10/14/2013'));
</script>
</head>
<body>
  <input type="button" 
       onclick="getDateDiff('10/18/2013','10/14/2013')" 
       value="clickHere()" />

</body>
</html>

#6


9  

function DateDiff(date1, date2) {
    date1.setHours(0);
    date1.setMinutes(0, 0, 0);
    date2.setHours(0);
    date2.setMinutes(0, 0, 0);
    var datediff = Math.abs(date1.getTime() - date2.getTime()); // difference 
    return parseInt(datediff / (24 * 60 * 60 * 1000), 10); //Convert values days and return value      
}

#7


9  

use Moment.js for all your JavaScript related date-time calculation

使用Moment.js进行所有与JavaScript相关的日期时间计算

Answer to your question is:

回答你的问题是:

var a = moment([2007, 0, 29]);   
var b = moment([2007, 0, 28]);    
a.diff(b) // 86400000  

Complete details can be found here

完整的细节可以在这里找到

#8


5  

var d1=new Date(2011,0,1); // jan,1 2011
var d2=new Date(); // now

var diff=d2-d1,sign=diff<0?-1:1,milliseconds,seconds,minutes,hours,days;
diff/=sign; // or diff=Math.abs(diff);
diff=(diff-(milliseconds=diff%1000))/1000;
diff=(diff-(seconds=diff%60))/60;
diff=(diff-(minutes=diff%60))/60;
days=(diff-(hours=diff%24))/24;

console.info(sign===1?"Elapsed: ":"Remains: ",
             days+" days, ",
             hours+" hours, ",
             minutes+" minutes, ",
             seconds+" seconds, ",
             milliseconds+" milliseconds.");

#9


4  

With momentjs it's simple:

使用momentjs很简单:

moment("2016-04-08").fromNow();

#10


3  

If you are using moment.js then it is pretty simple to find date difference.

如果您使用的是moment.js,那么找到日期差异非常简单。

var now  = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";

moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")

#11


3  

Sorry but flat millisecond calculation is not reliable Thanks for all the responses, but few of the functions I tried are failing either on 1. A date near today's date 2. A date in 1970 or 3. A date in a leap year.

抱歉,平坦的毫秒计算不可靠感谢所有的回复,但我尝试过的功能很少都失败了1.今天的日期附近的日期2. 1970年的日期或3.闰年的日期。

Approach that best worked for me and covers all scenario e.g. leap year, near date in 1970, feb 29 etc.

最适合我的方法,涵盖所有方案,例如闰年,1970年即将到来,29日等

var someday = new Date("8/1/1985");
var today = new Date();
var years = today.getFullYear() - someday.getFullYear();

// Reset someday to the current year.
someday.setFullYear(today.getFullYear());

// Depending on when that day falls for this year, subtract 1.
if (today < someday)
{
    years--;
}
document.write("Its been " + years + " full years.");

#12


1  

function DateDiff(b, e)
{
    let
        endYear = e.getFullYear(),
        endMonth = e.getMonth(),
        years = endYear - b.getFullYear(),
        months = endMonth - b.getMonth(),
        days = e.getDate() - b.getDate();
    if (months < 0)
    {
        years--;
        months += 12;
    }
    if (days < 0)
    {
        months--;
        days += new Date(endYear, endMonth, 0).getDate();
    }
    return [years, months, days];
}

[years, months, days] = DateDiff(
    new Date("October 21, 1980",
    new Date("July 11, 2017"))); // 36 8 20

#13


0  

you can also use this very easy to use date manipulation library http://www.datejs.com/

你也可以使用这个非常容易使用的日期操作库http://www.datejs.com/

ex:

例如:

// Add 3 days to Today
Date.today().add(3).days();

(Works very well with date formatting libraries)

(适用于日期格式库)

#14


0  

To simplify this I wrote a component that works similarly to the moment.js solutions without the overhead of using the entire library. It also allows you to skip all of the manual arithmetic for converting between time units. You can input two Date objects and find the difference between them in milliseconds, seconds, minutes, hours, days, weeks, months, or years.

为了简化这一点,我编写了一个与moment.js解决方案类似的组件,没有使用整个库的开销。它还允许您跳过所有手动算术以在时间单位之间进行转换。您可以输入两个Date对象,并以毫秒,秒,分钟,小时,天,周,月或年为单位查找它们之间的差异。

For example:

例如:

var date1 = new Date('January 24, 1984 09:41:00');
var date2 = new Date('June 29, 2007 18:45:10');

dateDiff(date1, date2, 'milliseconds');   // => 739357450000
dateDiff(date1, date2, 'seconds');        // => 739357450
dateDiff(date1, date2, 'minutes');        // => 12322624
dateDiff(date1, date2, 'hours');          // => 205377
dateDiff(date1, date2, 'days');           // => 8557
dateDiff(date1, date2, 'weeks');          // => 1222
dateDiff(date1, date2, 'months');         // => 281
dateDiff(date1, date2, 'years');          // => 23

Feel free to import the component to use the dateDiff() method in your project.

随意导入组件以在项目中使用dateDiff()方法。

#1


150  

Assuming you have two Date objects, you can just subtract them to get the difference in milliseconds:

假设你有两个Date对象,你可以减去它们以获得毫秒级的差异:

var difference = date2 - date1;

From there, you can use simple arithmetic to derive the other values.

从那里,您可以使用简单的算法来导出其他值。

#2


56  

var DateDiff = {

    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000));
    },

    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000*7));
    },

    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();

        return (d2M+12*d2Y)-(d1M+12*d1Y);
    },

    inYears: function(d1, d2) {
        return d2.getFullYear()-d1.getFullYear();
    }
}

var dString = "May, 20, 1984";

var d1 = new Date(dString);
var d2 = new Date();

document.write("<br />Number of <b>days</b> since "+dString+": "+DateDiff.inDays(d1, d2));
document.write("<br />Number of <b>weeks</b> since "+dString+": "+DateDiff.inWeeks(d1, d2));
document.write("<br />Number of <b>months</b> since "+dString+": "+DateDiff.inMonths(d1, d2));
document.write("<br />Number of <b>years</b> since "+dString+": "+DateDiff.inYears(d1, d2));

Code sample taken from here.

代码示例取自此处。

#3


26  

Another solution is convert difference to a new Date object and get that date's year(diff from 1970), month, day etc.

另一个解决方案是将差异转换为新的Date对象并获取该日期的年份(1970年的差异),月,日等。

var date1 = new Date(2010, 6, 17);
var date2 = new Date(2013, 12, 18);
var diff = new Date(date2.getTime() - date1.getTime());
// diff is: Thu Jul 05 1973 04:00:00 GMT+0300 (EEST)

console.log(diff.getUTCFullYear() - 1970); // Gives difference as year
// 3

console.log(diff.getUTCMonth()); // Gives month count of difference
// 6

console.log(diff.getUTCDate() - 1); // Gives day count of difference
// 4

So difference is like "3 years and 6 months and 4 days". If you want to take difference in a human readable style, that can help you.

所以差异就像“3年6个月4天”。如果你想在人类可读的风格上有所不同,那可以帮助你。

#4


19  

Expressions like "difference in days" are never as simple as they seem. If you have the following dates:

像“天差”这样的表达从来就不像看起来那么简单。如果您有以下日期:

d1: 2011-10-15 23:59:00
d1: 2011-10-16 00:01:00

the difference in time is 2 minutes, should the "difference in days" be 1 or 0? Similar issues arise for any expression of the difference in months, years or whatever since years, months and days are of different lengths and different times (e.g. the day that daylight saving starts is 1 hour shorter than usual and two hours shorter than the day that it ends).

时间的差异是2分钟,“天数差异”应该是1还是0?类似的问题出现在几个月,几年或其他任何表达的差异,因为年,月和日具有不同的长度和不同的时间(例如,夏令时开始的日子比通常短1小时,比那天短2小时)它结束了)。

Here is a function for a difference in days that ignores the time, i.e. for the above dates it returns 1.

这是一个忽略时间的天数差异的函数,即上面的日期它返回1。

/*
   Get the number of days between two dates - not inclusive.

   "between" does not include the start date, so days
   between Thursday and Friday is one, Thursday to Saturday
   is two, and so on. Between Friday and the following Friday is 7.

   e.g. getDaysBetweenDates( 22-Jul-2011, 29-jul-2011) => 7.

   If want inclusive dates (e.g. leave from 1/1/2011 to 30/1/2011),
   use date prior to start date (i.e. 31/12/2010 to 30/1/2011).

   Only calculates whole days.

   Assumes d0 <= d1
*/
function getDaysBetweenDates(d0, d1) {

  var msPerDay = 8.64e7;

  // Copy dates so don't mess them up
  var x0 = new Date(d0);
  var x1 = new Date(d1);

  // Set to noon - avoid DST errors
  x0.setHours(12,0,0);
  x1.setHours(12,0,0);

  // Round to remove daylight saving errors
  return Math.round( (x1 - x0) / msPerDay );
}

This can be more concise:

这可以更简洁:

/*  Return number of days between d0 and d1.
**  Returns positive if d0 < d1, otherwise negative.
**
**  e.g. between 2000-02-28 and 2001-02-28 there are 366 days
**       between 2015-12-28 and 2015-12-29 there is 1 day
**       between 2015-12-28 23:59:59 and 2015-12-29 00:00:01 there is 1 day
**       between 2015-12-28 00:00:01 and 2015-12-28 23:59:59 there are 0 days
**        
**  @param {Date} d0  - start date
**  @param {Date} d1  - end date
**  @returns {number} - whole number of days between d0 and d1
**
*/
function daysDifference(d0, d1) {
  var diff = new Date(+d1).setHours(12) - new Date(+d0).setHours(12);
  return Math.round(diff/8.64e7);
}

// Simple formatter
function formatDate(date){
  return [date.getFullYear(),('0'+(date.getMonth()+1)).slice(-2),('0'+date.getDate()).slice(-2)].join('-');
}

// Examples
[[new Date(2000,1,28), new Date(2001,1,28)],  // Leap year
 [new Date(2001,1,28), new Date(2002,1,28)],  // Not leap year
 [new Date(2017,0,1),  new Date(2017,1,1)] 
].forEach(function(dates) {
  document.write('From ' + formatDate(dates[0]) + ' to ' + formatDate(dates[1]) +
                 ' is ' + daysDifference(dates[0],dates[1]) + ' days<br>');
});

#5


16  

<html lang="en">
<head>
<script>
function getDateDiff(time1, time2) {
  var str1= time1.split('/');
  var str2= time2.split('/');

  //                yyyy   , mm       , dd
  var t1 = new Date(str1[2], str1[0]-1, str1[1]);
  var t2 = new Date(str2[2], str2[0]-1, str2[1]);

  var diffMS = t1 - t2;    
  console.log(diffMS + ' ms');

  var diffS = diffMS / 1000;    
  console.log(diffS + ' ');

  var diffM = diffS / 60;
  console.log(diffM + ' minutes');

  var diffH = diffM / 60;
  console.log(diffH + ' hours');

  var diffD = diffH / 24;
  console.log(diffD + ' days');
  alert(diffD);
}

//alert(getDateDiff('10/18/2013','10/14/2013'));
</script>
</head>
<body>
  <input type="button" 
       onclick="getDateDiff('10/18/2013','10/14/2013')" 
       value="clickHere()" />

</body>
</html>

#6


9  

function DateDiff(date1, date2) {
    date1.setHours(0);
    date1.setMinutes(0, 0, 0);
    date2.setHours(0);
    date2.setMinutes(0, 0, 0);
    var datediff = Math.abs(date1.getTime() - date2.getTime()); // difference 
    return parseInt(datediff / (24 * 60 * 60 * 1000), 10); //Convert values days and return value      
}

#7


9  

use Moment.js for all your JavaScript related date-time calculation

使用Moment.js进行所有与JavaScript相关的日期时间计算

Answer to your question is:

回答你的问题是:

var a = moment([2007, 0, 29]);   
var b = moment([2007, 0, 28]);    
a.diff(b) // 86400000  

Complete details can be found here

完整的细节可以在这里找到

#8


5  

var d1=new Date(2011,0,1); // jan,1 2011
var d2=new Date(); // now

var diff=d2-d1,sign=diff<0?-1:1,milliseconds,seconds,minutes,hours,days;
diff/=sign; // or diff=Math.abs(diff);
diff=(diff-(milliseconds=diff%1000))/1000;
diff=(diff-(seconds=diff%60))/60;
diff=(diff-(minutes=diff%60))/60;
days=(diff-(hours=diff%24))/24;

console.info(sign===1?"Elapsed: ":"Remains: ",
             days+" days, ",
             hours+" hours, ",
             minutes+" minutes, ",
             seconds+" seconds, ",
             milliseconds+" milliseconds.");

#9


4  

With momentjs it's simple:

使用momentjs很简单:

moment("2016-04-08").fromNow();

#10


3  

If you are using moment.js then it is pretty simple to find date difference.

如果您使用的是moment.js,那么找到日期差异非常简单。

var now  = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";

moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")

#11


3  

Sorry but flat millisecond calculation is not reliable Thanks for all the responses, but few of the functions I tried are failing either on 1. A date near today's date 2. A date in 1970 or 3. A date in a leap year.

抱歉,平坦的毫秒计算不可靠感谢所有的回复,但我尝试过的功能很少都失败了1.今天的日期附近的日期2. 1970年的日期或3.闰年的日期。

Approach that best worked for me and covers all scenario e.g. leap year, near date in 1970, feb 29 etc.

最适合我的方法,涵盖所有方案,例如闰年,1970年即将到来,29日等

var someday = new Date("8/1/1985");
var today = new Date();
var years = today.getFullYear() - someday.getFullYear();

// Reset someday to the current year.
someday.setFullYear(today.getFullYear());

// Depending on when that day falls for this year, subtract 1.
if (today < someday)
{
    years--;
}
document.write("Its been " + years + " full years.");

#12


1  

function DateDiff(b, e)
{
    let
        endYear = e.getFullYear(),
        endMonth = e.getMonth(),
        years = endYear - b.getFullYear(),
        months = endMonth - b.getMonth(),
        days = e.getDate() - b.getDate();
    if (months < 0)
    {
        years--;
        months += 12;
    }
    if (days < 0)
    {
        months--;
        days += new Date(endYear, endMonth, 0).getDate();
    }
    return [years, months, days];
}

[years, months, days] = DateDiff(
    new Date("October 21, 1980",
    new Date("July 11, 2017"))); // 36 8 20

#13


0  

you can also use this very easy to use date manipulation library http://www.datejs.com/

你也可以使用这个非常容易使用的日期操作库http://www.datejs.com/

ex:

例如:

// Add 3 days to Today
Date.today().add(3).days();

(Works very well with date formatting libraries)

(适用于日期格式库)

#14


0  

To simplify this I wrote a component that works similarly to the moment.js solutions without the overhead of using the entire library. It also allows you to skip all of the manual arithmetic for converting between time units. You can input two Date objects and find the difference between them in milliseconds, seconds, minutes, hours, days, weeks, months, or years.

为了简化这一点,我编写了一个与moment.js解决方案类似的组件,没有使用整个库的开销。它还允许您跳过所有手动算术以在时间单位之间进行转换。您可以输入两个Date对象,并以毫秒,秒,分钟,小时,天,周,月或年为单位查找它们之间的差异。

For example:

例如:

var date1 = new Date('January 24, 1984 09:41:00');
var date2 = new Date('June 29, 2007 18:45:10');

dateDiff(date1, date2, 'milliseconds');   // => 739357450000
dateDiff(date1, date2, 'seconds');        // => 739357450
dateDiff(date1, date2, 'minutes');        // => 12322624
dateDiff(date1, date2, 'hours');          // => 205377
dateDiff(date1, date2, 'days');           // => 8557
dateDiff(date1, date2, 'weeks');          // => 1222
dateDiff(date1, date2, 'months');         // => 281
dateDiff(date1, date2, 'years');          // => 23

Feel free to import the component to use the dateDiff() method in your project.

随意导入组件以在项目中使用dateDiff()方法。