Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the time difference between 2 date time values

Tags:

date

time

I am trying to calculate the time difference between 2 date time strings.

I have 2 inputs where the input string is something like this "1:00 PM" and the second one "3:15 PM". I want to know the time difference. So for the above example I want to display 3.15

What I have done:

  1. Converted the time to a 24 hours format. So "1:00 PM" becomes "13:00:00"
  2. Appended the new time to a date like so: new Date("1970-1-1 13:00:00")
  3. Calculated the difference like so:

Code:

var total = Math.round(((new Date("1970-1-1 " + end_time) - 
                         new Date("1970-1-1 " + start_time) ) / 1000 / 3600) , 2 )

But the total is always returning integers and not decimals, so the difference between "1:00 PM" and "3:15 PM" is 2 not 2.15.

I have also tried this (using jQuery, but that is irrelevant):

$('#to_ad,#from_ad').change(function(){
    $('#total_ad').val( getDiffTime() );
});

function fixTimeString(time){
    var hours = Number(time.match(/^(\d+)/)[1]);
    var minutes = Number(time.match(/:(\d+)/)[1]);
    var AMPM = time.match(/\s(.*)$/)[1];
    if(AMPM == "PM" && hours<12) hours = hours+12;
    if(AMPM == "AM" && hours==12) hours = hours-12;
    var sHours = hours.toString();
    var sMinutes = minutes.toString();
    if(hours<10) sHours = "0" + sHours;
    if(minutes<10) sMinutes = "0" + sMinutes;
    return sHours + ':' + sMinutes + ':00';
}

function getDiffTime(){
    var start_time = fixTimeString($('#from_ad').val());
    var end_time = fixTimeString($('#to_ad').val());
    var start = new Date("1970-1-1 " + end_time).getTime(),
    end   = new Date("1970-1-1 " + start_time).getTime();
    return parseInt(((start  - end) / 1000 / 3600, 10)*100) / 100;
}

But the total_ad input is displaying only integer values.

How can I fix this problem?

like image 225
Mike Avatar asked Nov 11 '22 15:11

Mike


1 Answers

Math.round rounds to the nearest integer, multiply and divide instead

var start = new Date("1970-1-1 " + start_time).getTime(),
    end   = new Date("1970-1-1 " + end_time).getTime();

var total = (parseInt(((start-end) / 1000 / 3600)*100, 10)) / 100;

FIDDLE

When you take the time 15:15:00 and subtract 13:00:00, you're left with 2.15 hours, not 3.15, and this example would return 2.15 even without making sure there is only two decimals, but for other times that might not be the case.
You could also use toFixed(2), but that would leave you with 3.00 and not 3 etc.

like image 70
adeneo Avatar answered Dec 29 '22 07:12

adeneo