我想用天、小时、分钟、秒、毫秒、纳秒来计算日期差异。我该怎么做呢?


当前回答

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      
}

其他回答

假设你有两个Date对象,你可以减去它们,以毫秒为单位得到差值:

var difference = date2 - date1;

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

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

你问题的答案是:

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

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

这段代码将返回两个日期的差值(以天为单位):

const previous_date = new Date("2019-12-23");
const current_date = new Date();

const current_year = current_date.getFullYear();
const previous_date_year = 
previous_date.getFullYear();

const difference_in_years = current_year - 
previous_date_year;

let months = current_date.getMonth();
months = months + 1; // for making the indexing 
// of months from 1

for(let i = 0; i < difference_in_years; i++){
months = months + 12;
}

let days = current_date.getDate();

days = days + (months * 30.417);

console.log(`The days between ${current_date} and 
${previous_date} are : ${days} (approximately)`);
var DateDiff = {
 
    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
 
        return Math.floor((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));

代码样本从这里。

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

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

时间差2分钟,“天数差”应该是1还是0?类似的问题也出现在任何以月、年或其他形式表示的差异中,因为年、月和日的长度和时间不同(例如,夏令时开始的那一天比平时短1小时,比夏令时结束的那一天短2小时)。

这里是一个忽略时间的天数差函数,即对于上述日期,它返回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 );
}

这可以更简洁:

/* 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>'); });