How to calculate date difference in JavaScript?

前端 未结 18 1742
执笔经年
执笔经年 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:06

    Sorry but flat millisecond calculation is not reliable Thanks for all the responses, but few of the functions I tried are failing either on 1. A date near today's date 2. A date in 1970 or 3. A date in a leap year.

    Approach that best worked for me and covers all scenario e.g. leap year, near date in 1970, feb 29 etc.

    var someday = new Date("8/1/1985");
    var today = new Date();
    var years = today.getFullYear() - someday.getFullYear();
    
    // Reset someday to the current year.
    someday.setFullYear(today.getFullYear());
    
    // Depending on when that day falls for this year, subtract 1.
    if (today < someday)
    {
        years--;
    }
    document.write("Its been " + years + " full years.");
    

提交回复
热议问题