2010-11-17 32 views
0

我得到24小時格式正確的持續時間,但對於12小時格式,如果我在上午11點到下午1:00給出錯誤,如果我在上午10點到上午11點之間進行修正,如果我在下午6點到下午7點之間給出正確的答案,那麼在下午我纔會面臨問題。12小時格式的時間期限問題

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

回答

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

} 
+0

下午到下午差異我得到時,我使用此代碼的一些問題。 – yopirates 2010-11-17 08:21:39

+0

你介意指出你有什麼問題嗎?當我在這裏嘗試時,它似乎對我有用:http://jsbin.com/oxado4這種行爲不是你想要的嗎? – 2010-11-17 08:31:30