简体   繁体   中英

javascript subtract two times from each other

So, I try to get a difference bewteen two times (not dates) but it doesn't work at all.

This is the javascript code I'm using now:

function getTimeBeforeClockIn() {
    $.ajax({
        url: '/ajax/get-trip-ideal-stop-time',
        type: 'GET',
        contentType: 'application/json',
        success: function (ideal_stop_time){
            var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
            m = checkTime(m);
            s = checkTime(s);
            var cur_time = h + ":" + m + ":" + s;
            console.log(cur_time);
            console.log(ideal_stop_time);
            var stime = (new Date(new Date().toDateString() + ' ' + ideal_stop_time));
            var time_difference = cur_time - stime;
            console.log(time_difference);
            document.getElementById('ideal_time_for_stop').innerHTML = time_difference;
        }
    });

    var t = setTimeout(getTimeBeforeClockIn, 500);
}

The ajax call returns a string with the format hh:mm:ss so like 22:09:25

So I want the difference between a new Date(); object and a string (since the ajax call gets a string)

I want to get the difference between the current time and the time from the ajax call. This can be positive and negative. So if the time is negative, then it should get an output like - 00:08:25 format: hh:mm:ss else it needs an output with a +

hope someone can help me with this?

You want to do:

var time_difference=today-stime;

This will give you the number of seconds between those two Date objects. Then convert those seconds into the time format that you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM