Search code examples
javascriptnode.jsangularjavascript-objectsnode-modules

Time difference function giving negative value


I am using below logic to calculate the time difference.

However, this is giving wrong result value when days > 1. Please help simplifying the code.

I will be using the time difference logic in angular framework.

const startDate = new Date(form.value.startDate);
const endDate = new Date();
const dateDiff = this.calculateDateDifference(startDate, endDate);

calculateDateDifference(startDate, endDate) {
    const difference = startDate.getTime() - endDate.getTime();

    const seconds = Math.floor((difference / 1000) % 60);
    const minutes = Math.floor((difference / (1000 * 60)) % 60);
    const hours = Math.floor((difference / (1000 * 60 * 60)) % 24);
    const days = Math.floor(difference / (1000 * 60 * 60 * 24));

    console.log(days + ' days ' + hours + ' hours ' + minutes + ' minutes ' + seconds + ' seconds');
    if (days > 1) {
        return `${days} Days, ${hours} Hours, ${minutes} Mins`;
    } else {
        return `${hours} Hours, ${minutes} Mins`;
    }
}

Solution

  • According to docs

    The getTime() method of Date instances returns the number of milliseconds for this date since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.

    startDate should have less milliseconds since the 1970 then endDate,

    So, the right option is:

    const difference = endDate.getTime() - startDate.getTime();