Calculate duration between two dates in javascript

I need to calculate the duration between two datetimes in JavaScript. I tried this code:

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!

var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} today = mm+'/'+dd+'/'+yyyy;  //Current Date
console.log("current date"+today);


var valuestart ="8:00 AM";
var valuestop = "4:00 PM";//$("select[name='timestop']").val();

//create date format          
var timeStart = new Date("01/01/2007 " + valuestart).getHours();
var timeEnd = new Date("01/01/2007 " + valuestop).getHours();

var hourDiff = timeEnd - timeStart;             
console.log("duration"+hourDiff);

From this I can get the current date and duration. But when I replace the date "01.01.2007" with the variable "today", I get the result as NaN. Please lead me to where I am wrong. Thanks in advance.

+3
source share
3 answers

Try the following:

        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!

        var yyyy = today.getFullYear();
        if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} today = dd+'/'+mm+'/'+yyyy;  //Current Date

        var valuestart ="8:00 AM";
        var valuestop = "4:00 PM";//$("select[name='timestop']").val();

        //create date format  
        var timeStart = new Date(today + " " + valuestart).getHours();
        var timeEnd = new Date(today + " " + valuestop).getHours();

        var hourDiff = timeEnd - timeStart;  
        alert("duration:"+hourDiff);
+2
source

You must work in the era of milliseconds. The idea is to convert everything to an epoch millis view , do your calculations , and then return to another format if necessary.

:

+2

today is of type Date, whereas "01/01/2007" is a string. Trying to combine a Date object with "8:00 AM" will not work. You will have to turn today's variable into a string or use today.setHours (8)

+1
source

All Articles