How to calculate date difference in JavaScript?

前端 未结 18 2107
执笔经年
执笔经年 2020-11-22 03:41

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

18条回答
  •  忘掉有多难
    2020-11-22 03:56

    Ok, there are a bunch of ways you can do that. Yes, you can use plain old JS. Just try:

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

    Let's emulate passage using Date.prototype.setMinutes and make sure we are in range.

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

    Alternatively you could use some library like js-joda, where you can easily do things like this (directly from docs):

    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
    

    There are plenty more libraries ofc, but js-joda has an added bonus of being available also in Java, where it has been extensively tested. All those tests have been migrated to js-joda, it's also immutable.

提交回复
热议问题