2013-07-24 255 views
1

我有這個功能的Javascript時間差計算

function timeCalculator(form) 
{ 
    var currentTimeAndDate = new Date(); 
    var userTimeAndDate = form.userDate.value; 
    var userUTCOffset2 = form.userUTCOffset.value; 
    var userDate = new Date(userTimeAndDate); 
    var tzDifference = currentTimeAndDate.getTimezoneOffset() + (userUTCOffset2 - currentTimeAndDate.getTimezoneOffset()); 
    var timeDifference = new Date((userDate.getTime()+(tzDifference*60*1000))-(currentTimeAndDate.getTime()+(userDate.getTimezoneOffset()*60*1000))); 

    var hours = Math.floor(timeDifference.getTime()/36e5), 
    minutes = Math.floor(timeDifference.getTime() % 36e5/60000), 
    seconds = Math.floor(timeDifference.getTime() % 60000/1000); 

    document.getElementById('result').innerHTML = "There is exactly "+hours+" hours,"+minutes+"minutes and "+seconds+" seconds left until your specified time."; 
} 

什麼這是應該做的是用戶輸入的形式偏移和基於它計算多少時間留到時間,日期和UTC那一點。分鐘和秒鐘似乎工作正常,但時間有問題。任何人有任何建議或可能有不同的方法來這樣的事情?另外我該如何在差異中添加日,月,年?

回答

2

爲此,我建議使用moment.js。它會爲你節省很多的痛苦。

function timeCalculator(form) 
{ 
    // get a moment based on the user input 
    var m = moment(form.userDate.value).zone(form.userUTCOffset.value); 

    // calculate a duration of time passed between now and that moment 
    var now = moment(); 
    var d = moment.duration(m - now); 

    // build your output string 
    var s = d.hours() + " hours, " + 
      d.minutes() + " minutes, and " + 
      d.seconds() + " seconds"; 

    // set the output html 
    document.getElementById('result').innerHTML = "There are exactly " + s + 
              " left until your specified time."; 
} 

這假定未來的日期選擇,並且你總是希望顯示小時,分鐘和秒。

你可能會考慮,而不是更廣義的做法,這表明由於或剩餘時間的近似

function timeCalculator(form) 
{ 
    // get a moment based on the user input 
    var m = moment(form.userDate.value).zone(form.userUTCOffset.value); 

    // get a humanized duration string 
    var s = m.fromNow(true); 

    // set the output html 
    document.getElementById('result').innerHTML = "There are " + s + 
              " left until your specified time."; 
} 

參見文檔上fromNow有關預期輸出的詳細信息。

順便說一句,傳遞格式和設置結果在硬編碼元素中似乎有點奇怪。您可能只想傳遞表單值並返回字符串結果,讓函數的調用者處理它們來自哪裏並前往。

+0

這很酷。非常感謝。 –

+0

如果這可以解決您的問題,請將其標記爲接受的答案。謝謝。 –

+0

感謝您指出了moment.js來拯救我們免受痛苦。 – Herr