Difference between two dates in years, months, days in JavaScript

前端 未结 26 2861
执念已碎
执念已碎 2020-11-22 07:18

I\'ve been searching for 4 hours now, and have not found a solution to get the difference between two dates in years, months, and days in JavaScript, like: 10th of April 201

26条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 07:49

    I know it is an old thread, but I'd like to put my 2 cents based on the answer by @Pawel Miech.

    It is true that you need to convert the difference into milliseconds, then you need to make some math. But notice that, you need to do the math in backward manner, i.e. you need to calculate years, months, days, hours then minutes.

    I used to do some thing like this:

        var mins;
        var hours;
        var days;
        var months;
        var years;
    
        var diff = new Date() - new Date(yourOldDate);  
    // yourOldDate may be is coming from DB, for example, but it should be in the correct format ("MM/dd/yyyy hh:mm:ss:fff tt")
    
        years = Math.floor((diff) / (1000 * 60 * 60 * 24 * 365));
        diff = Math.floor((diff) % (1000 * 60 * 60 * 24 * 365));
        months = Math.floor((diff) / (1000 * 60 * 60 * 24 * 30));
        diff = Math.floor((diff) % (1000 * 60 * 60 * 24 * 30));
        days = Math.floor((diff) / (1000 * 60 * 60 * 24));
        diff = Math.floor((diff) % (1000 * 60 * 60 * 24));
        hours = Math.floor((diff) / (1000 * 60 * 60));
        diff = Math.floor((diff) % (1000 * 60 * 60));
        mins = Math.floor((diff) / (1000 * 60));
    

    But, of course, this is not precise because it assumes that all years have 365 days and all months have 30 days, which is not true in all cases.

提交回复
热议问题