Mike
Mike

Reputation: 8877

Time between two times on current date

I am trying to calculate the time between two times on the current date using JavaScript. There are other questions similar to this one, but none seem to work, and few with many upvotes that I can find.

I have the following, which fails on the line: var diff = new Date(time1 - time2);, which always gives me an invalid Date when alerted, so it is clearly failing. I cannot work out why.

The initial date is added in the format of: hh:mm:ss in an input field. I am using jQuery.

$(function(){

$('#goTime').click(function(){
  var currentDate = new Date();

  var dateString = (strpad(currentDate.getDate()) +'-'+ strpad(currentDate.getMonth()+1)+'-'+currentDate.getFullYear()+' '+ $('#starttime').val());

  var time1 = new Date(dateString).getTime();
  var time2 = new Date().getTime();

  var diff = new Date(time1 - time2);

  var hours = diff.getHours();
  var minutes = diff.getMinutes();
  var seconds = diff.getMinutes();

  alert(hours + ':' + minutes + ':' + seconds);

});
  });
  function strpad(val){ 
        return (!isNaN(val) && val.toString().length==1)?"0"+val:val; 
  }

dateString is equal to: 14-01-2013 23:00

Upvotes: 0

Views: 1873

Answers (4)

Justin Bicknell
Justin Bicknell

Reputation: 4808

If you are trying to calculate the time difference between two dates, then you do not need to create a new date object to do that.

  var time1 = new Date(dateString).getTime();
  var time2 = new Date().getTime();

  var diff = time1 - time2;// number of milliseconds 

  var seconds = diff/1000;
  var minutes = seconds/60;
  var hours = minutes/60;

Edit: You will want to take into account broofa's answer as well to make sure your date string is correctly formatted

The getTime function returns the number of milliseconds since Jan 1, 1970. So by subtracting the two values you are left with the number of milliseconds between each date object. If you were to pass that value into the Date constructor, the resulting date object would not be what you are expecting. see getTime

Upvotes: 0

Bergi
Bergi

Reputation: 664548

You are experiencing an invalid time in your datestring. time1 is NaN, and so diff will be. It might be better to use this:

var date = new Date();
var match = /^(\d+):(\d+):(\d+)$/.exec($('#starttime').val()); // enforcing format
if (!match)
    return alert("Invalid input!"); // abort
date.setHours(parseInt(match[1], 10));
date.setMinutes(parseInt(match[2], 10));
date.setSeconds(parseInt(match[3], 10));

var diff = Date.now() - date;

Upvotes: 0

Mattias Buelens
Mattias Buelens

Reputation: 20159

dd-MM-yyyy HH:mm is not recognized as a valid time format by new Date(). You have a few options though:

  • Use slashes instead of dashes: dd/MM/yyyy HH:mm date strings are correctly parsed.
  • Use ISO date strings: yyyy-MM-dd HH:mm are also recognized.
  • Build the Date object yourself.

For the second option, since you only really care about the time, you could just split the time string yourself and pass them to Date.setHours(h, m, s):

var timeParts = $('#starttime').val().split(':', 2);
var time1 = new Date();
time1.setHours(timeParts[0], timeParts[1]);

Upvotes: 0

broofa
broofa

Reputation: 38122

You have the fields in dateString backwards. Swap the year and day fields...

> new Date('14-01-2013 23:00')
Invalid Date
> new Date('2013-01-14 23:00')
Mon Jan 14 2013 23:00:00 GMT-0800 (PST)

Upvotes: 3

Related Questions