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


当前回答

有很多方法可以做到这一点。 是的,你可以使用普通的旧JS。试试:

let dt1 = new Date()
let dt2 = new Date()

让我们使用Date.prototype.setMinutes模拟通道,并确保我们在范围内。

dt1.setMinutes(7)
dt2.setMinutes(42)
console.log('Elapsed seconds:',(dt2-dt1)/1000)

或者你也可以使用一些像js-joda这样的库,在那里你可以很容易地做这样的事情(直接从文档中):

var dt1 = LocalDateTime.parse("2016-02-26T23:55:42.123");
var dt2 = dt1
  .plusYears(6)
  .plusMonths(12)
  .plusHours(2)
  .plusMinutes(42)
  .plusSeconds(12);

// obtain the duration between the two dates
dt1.until(dt2, ChronoUnit.YEARS); // 7
dt1.until(dt2, ChronoUnit.MONTHS); // 84
dt1.until(dt2, ChronoUnit.WEEKS); // 356
dt1.until(dt2, ChronoUnit.DAYS); // 2557
dt1.until(dt2, ChronoUnit.HOURS); // 61370
dt1.until(dt2, ChronoUnit.MINUTES); // 3682242
dt1.until(dt2, ChronoUnit.SECONDS); // 220934532

有更多的ofc库,但js-joda还有一个额外的好处,它也可以在Java中使用,在Java中已经进行了广泛的测试。所有这些测试都已迁移到js-joda,它也是不可变的。

其他回答

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      
}

使用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)`);

我做了一个下面的函数来得到现在和“2021-02-26T21:50:42.123”之间的区别。

差值返回以毫秒为单位的答案,所以我使用以下公式进行转换:

(1000 * 3600 * 24).

function getDiff(dateAcquired) {
      let calDiff = Math.floor(
        (new Date() - new Date(dateAcquired)) / (1000 * 3600 * 24)
      );
      return calDiff;
    }
    console.log(getDiff("2021-02-26T21:50:42.123"));
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.");