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

时间:2010-11-17 07:09:32

标签: 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;

    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;
    }

2 个答案:

答案 0 :(得分:0)

为什么不使用javascript的Date类?

http://www.w3schools.com/jsref/jsref_obj_date.asp

答案 1 :(得分:0)

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);

}