How to calculate date difference in JavaScript?

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

    This is how you can implement difference between dates without a framework.

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

提交回复
热议问题