简体   繁体   English

javascript彼此相减两次

[英]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: 这是我现在使用的javascript代码:

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 ajax调用返回格式为hh:mm:ss的字符串,例如22:09:25

So I want the difference between a new Date(); 所以我想要一个new Date();之间的区别new Date(); object and a string (since the ajax call gets a string) 对象和一个string (因为ajax调用获取一个字符串)

I want to get the difference between the current time and the time from the ajax call. 我想得到当前时间和来自ajax调用的时间之间的时差。 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 + 因此,如果时间为负数,则应获得类似于- 00:08:25 : - 00:08:25 : - 00:08:25格式的输出: hh:mm:ss否则它需要带有+的输出

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. 这将为您提供这两个Date对象之间的秒数。 Then convert those seconds into the time format that you want. 然后将这些秒转换为所需的时间格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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