Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 12小时格式的持续时间问题_Javascript - Fatal编程技术网

Javascript 12小时格式的持续时间问题

Javascript 12小时格式的持续时间问题,javascript,Javascript,对于24小时格式,我得到了正确的持续时间,但是对于12小时格式,如果我给出上午11:00到下午1:00,我得到了错误。如果我给出上午10:00到11:00的时间,它会纠正错误;如果我给出下午6:00到7:00的时间,它只会正确给出上午到下午的时间,我面临问题 function autoChangeDuration() { var diff1 = "00:00"; var start = document.getElementById("startTime").value;

对于24小时格式,我得到了正确的持续时间,但是对于12小时格式,如果我给出上午11:00到下午1:00,我得到了错误。如果我给出上午10:00到11:00的时间,它会纠正错误;如果我给出下午6:00到7:00的时间,它只会正确给出上午到下午的时间,我面临问题

function autoChangeDuration() {
    var diff1 = "00:00";
    var start = document.getElementById("startTime").value;

    var end = document.getElementById("endTime").value;

    if (start > end) {
        document.getElementById("duration").value = diff1;
    } else {
        var space1 = start.split(' ');
        var space2 = end.split(' ');

        s = space1[0].split(':');
        e = space2[0].split(':');

        var diff;

        min = e[1] - s[1];
        hour_carry = 0;

        if (min < 0) {
            min += 60;
            hour_carry += 1;
        }

        hour = e[0] - s[0] - hour_carry;
        diff = hour + ":" + min;
        document.getElementById("duration").value = diff;
    }

为什么不直接使用javascript的日期类呢


我从配置类中获取日期和时间格式。我在jsp中使用此函数。当我使用此代码时,我发现pm与pm之间存在一些问题。您介意指出您遇到的问题吗?当我在这里尝试时,它似乎对我有效:这种行为不是你想要的吗?
function toDate(s) {

    // the date doesn't matter, as long as they're the same, since we'll
    // just use them to compare. passing "10:20 pm" will yield 22:20.
    return new Date("2010/01/01 " + s);

}

function toTimeString(diffInMs) {

   // Math.max makes sure that you'll get '00:00' if start > end.

   var diffInMinutes = Math.max(0, Math.floor(diffInMs / 1000 / 60));
   var diffInHours = Math.max(0, Math.floor(diffInMinutes / 60));

   diffInMinutes = diffInMinutes % 60;

   return [
       ('0'+diffInHours).slice(-2),
       ('0'+diffInMinutes).slice(-2)
   ].join(':');

}

function autoChangeDuration()
{
    var start = document.getElementById("startTime").value;
    var end = document.getElementById("endTime").value;

    start = toDate(start);
    end = toDate(end);

    var diff = (end - start);

    document.getElementById("duration").value = toTimeString(diff);

}