How do I get the difference between two Dates in JavaScript?

前端 未结 16 2351
北海茫月
北海茫月 2020-11-22 03:03

I\'m creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date.

16条回答
  •  隐瞒了意图╮
    2020-11-22 03:45

    See JsFiddle DEMO

        var date1 = new Date();    
        var date2 = new Date("2025/07/30 21:59:00");
        //Customise date2 for your required future time
    
        showDiff();
    
    function showDiff(date1, date2){
    
        var diff = (date2 - date1)/1000;
        diff = Math.abs(Math.floor(diff));
    
        var days = Math.floor(diff/(24*60*60));
        var leftSec = diff - days * 24*60*60;
    
        var hrs = Math.floor(leftSec/(60*60));
        var leftSec = leftSec - hrs * 60*60;
    
        var min = Math.floor(leftSec/(60));
        var leftSec = leftSec - min * 60;
    
        document.getElementById("showTime").innerHTML = "You have " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds before death.";
    
    setTimeout(showDiff,1000);
    }
    

    for your HTML Code:

提交回复
热议问题