Mike
Mike

Reputation: 2923

How to calculate the time difference between 2 date time values

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?

Upvotes: 5

Views: 8765

Answers (2)

Andrews Kalinovski
Andrews Kalinovski

Reputation: 24

This is how I calculate it:

    calculateDiff();

function calculateDiff(){
        _start = "7:00 AM";
        _end = "1:00 PM";

        _start_time = parseAMDate(_start);
        _end_time = parseAMDate(_end);

        if (_end_time < _start_time){
            _end_time = parseAMDate(_end,1);
        }

        var difference= _end_time - _start_time;

        var hours = Math.floor(difference / 36e5),
            minutes = Math.floor(difference % 36e5 / 60000);
        if (parseInt(hours) >= 0 ){
            if (minutes == 0){
                minutes = "00";
            }
            alert(hours+":"+minutes);
        }
    }

    function parseAMDate(input, next_day) {

        var dateReg = /(\d{1,2}):(\d{2})\s*(AM|PM)/;

        var hour, minute, result = dateReg.exec(input);

        if (result) {
            hour = +result[1];
            minute = +result[2];

            if (result[3] === 'PM' && hour !== 12) {
                hour += 12;
            }
        }
        if (!next_day) {
            return new Date(1970, 01, 01, hour, minute).getTime();
        }else{
            return new Date(1970, 01, 02, hour, minute).getTime();
        }
    }

Upvotes: 0

adeneo
adeneo

Reputation: 318182

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.

Upvotes: 1

Related Questions