6

I need to calculate the duration between two datetimes in JavaScript. I have 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 am able to get Current Date and duration. But when I replace the date "01/01/2007" with the variable "today", I am getting the result as NaN. Please guide me in where I am wrong. Thanks in advance.

laike9m
  • 18,344
  • 20
  • 107
  • 140
user2247744
  • 125
  • 1
  • 5
  • 12

5 Answers5

3

You should work on the epoch milliseconds. The idea is to transform everything to the epoch millis representation, perform your calculations, then go back to another format if needed.

There are many articles on the subject:

Community
  • 1
  • 1
Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
2

Try this :

        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);
Jérôme Teisseire
  • 1,518
  • 1
  • 16
  • 26
1

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

KJ Price
  • 5,774
  • 3
  • 21
  • 34
0

Maybe It's a little bit late. I second the answer from Christophe Roussy. First, calculate the difference in UTC format, then turn the unit - hour. I think it's easier to understand and maintain. Here's the code

var date1 = new Date(`some_valid_start_date_format`);
var date2 = new Date(`some_end_start_date_format`);

var duration = date2.valueOf() - date1.valueOf(); // The unit is millisecond
var hourDiff = parseInt(duration / (60 * 60 * 1000)) // Turn the duration into hour format
VincentTu
  • 1
  • 2
0

I tried luxon and it's very handy:

Given dt1 and dt2 as ISO representation of date time,

luxon.DateTime.fromISO(dt1).diff(
  luxon.DateTime.fromISO(dt2),
  ['years', 'months', 'days', 'hours', 'minutes', 'seconds']
).values
shawnzhu
  • 7,233
  • 4
  • 35
  • 51