How to calculate date difference in JavaScript?

前端 未结 18 1981
执笔经年
执笔经年 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 04:14

    function DateDiff(b, e)
    {
        let
            endYear = e.getFullYear(),
            endMonth = e.getMonth(),
            years = endYear - b.getFullYear(),
            months = endMonth - b.getMonth(),
            days = e.getDate() - b.getDate();
        if (months < 0)
        {
            years--;
            months += 12;
        }
        if (days < 0)
        {
            months--;
            days += new Date(endYear, endMonth, 0).getDate();
        }
        return [years, months, days];
    }
    
    [years, months, days] = DateDiff(
        new Date("October 21, 1980"),
        new Date("July 11, 2017")); // 36 8 20
    

提交回复
热议问题