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


当前回答

有很多方法可以做到这一点。 是的,你可以使用普通的旧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 getDateDiff(dateOne, dateTwo) {
        if(dateOne.charAt(2)=='-' & dateTwo.charAt(2)=='-'){
            dateOne = new Date(formatDate(dateOne));
            dateTwo = new Date(formatDate(dateTwo));
        }
        else{
            dateOne = new Date(dateOne);
            dateTwo = new Date(dateTwo);            
        }
        let timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
        let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
        let diffMonths = Math.ceil(diffDays/31);
        let diffYears = Math.ceil(diffMonths/12);

        let message = "Difference in Days: " + diffDays + " " +
                      "Difference in Months: " + diffMonths+ " " + 
                      "Difference in Years: " + diffYears;
        return message;
     }

    function formatDate(date) {
         return date.split('-').reverse().join('-');
    }

    console.log(getDateDiff("23-04-2017", "23-04-2018"));
            // the idea is to get time left for new year.
           // Not considering milliseconds as of now, but that 
           //  can be done
           
            var newYear = '1 Jan 2023';
            const secondsInAMin = 60;
            const secondsInAnHour = 60 * secondsInAMin;
            const secondsInADay = 24 * secondsInAnHour;

            function DateDiffJs() {
                var newYearDate = new Date(newYear);
                var currDate = new Date();

                var remainingSecondsInDateDiff = (newYearDate - currDate) / 1000;
                var days = Math.floor(remainingSecondsInDateDiff / secondsInADay);

                var remainingSecondsAfterDays = remainingSecondsInDateDiff - (days * secondsInADay);
                var hours = Math.floor(remainingSecondsAfterDays / secondsInAnHour);

                var remainingSecondsAfterhours = remainingSecondsAfterDays - (hours * secondsInAnHour);
                var mins = Math.floor(remainingSecondsAfterhours / secondsInAMin);

                var seconds = Math.floor(remainingSecondsAfterhours - (mins * secondsInAMin));


                console.log(`days :: ${days}`)
                console.log(`hours :: ${hours}`)
                console.log(`mins :: ${mins}`)
                console.log(`seconds :: ${seconds}`)

            }

            DateDiffJs();

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

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

有很多方法可以做到这一点。 是的,你可以使用普通的旧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,它也是不可变的。

this should work just fine if you just need to show what time left, since JavaScript uses frames for its time you'll have get your End Time - The Time RN after that we can divide it by 1000 since apparently 1000 frames = 1 seconds, after that you can use the basic math of time, but there's still a problem to this code, since the calculation is static, it can't compensate for the different day total in a year (360/365/366), the bunch of IF after the calculation is to make it null if the time is lower than 0, hope this helps even though it's not exactly what you're asking :)

var now = new Date();
var end = new Date("End Time");
var total = (end - now) ;
var totalD =  Math.abs(Math.floor(total/1000));

var years = Math.floor(totalD / (365*60*60*24));
var months = Math.floor((totalD - years*365*60*60*24) / (30*60*60*24));
var days = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24)/ (60*60*24));
var hours = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24)/ (60*60));
var minutes = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60)/ (60));
var seconds = Math.floor(totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60 - minutes*60);

var Y = years < 1 ? "" : years + " Years ";
var M = months < 1 ? "" : months + " Months ";
var D = days < 1 ? "" : days + " Days ";
var H = hours < 1 ? "" : hours + " Hours ";
var I = minutes < 1 ? "" : minutes + " Minutes ";
var S = seconds < 1 ? "" : seconds + " Seconds ";
var A = years == 0 && months == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0 ? "Sending" : " Remaining";

document.getElementById('txt').innerHTML = Y + M + D + H + I + S + A;