2016-09-23 108 views
2

所以我做了一個函數來確定我要多久等到巴斯到達:時間到計算器給出錯誤的答案

function arrival(arrtime){ 

      //convert to seconds 
      function toSeconds(time_str) { 
       // Extract hours, minutes and seconds 
       var parts = time_str.split(':'); 
       // compute and return total seconds 
       return (parts[0] * 3600) + (parts[1] * 60) + parts[2];// seconds 
      } 

      var a = new Date().getHours() + ":" + new Date().getMinutes() + ":" + new Date().getSeconds();//current time 

      var difference = toSeconds(arrtime) - toSeconds(a); 

      function sformat(s) { 
       var fm = [ 
         Math.floor(s/60/60/24), // DAYS 
         Math.floor(s/60/60) % 24, // HOURS 
         Math.floor(s/60) % 60, // MINUTES 
         s % 60 // SECONDS 
       ]; 
       return $.map(fm, function(v, i) { return ((v < 10) ? '0' : '') + v; }).join(':'); 
      } 

      if (difference > 0){ 
       result = sformat(difference); 
      } else if (difference < 1 && difference > -20) { 
       result = "Chegou!"; 
      } else if (difference <= -20) { 
       result = "Amanhã às " + arrtime; 
      } 

      return result; 
     } 
//usage example: 
arrival("16:30:00"); 

,但它給我回答錯了.... 一些計算必須是錯的,但對於我的生活我無法弄清楚!

回答

0

我在這裏找到的一個問題是您的toSeconds函數,而不是將所有秒加起來,而是將秒作爲一個字符串連接起來。以你的例子(16:30:00)爲例,你應該返回57600180000秒,當你應該返回57600 + 1800 + 00 = 59400秒。

試試這種方法,看看它是否讓你更接近發表評論,如果你有其他問題。

function toSeconds(time_str) { 
    // Extract hours, minutes and seconds 
    var parts = time_str.split(':'); 

    // compute and return total seconds 
    var hoursAsSeconds = parseInt(parts[0]) * 3600; 
    var minAsSeconds = parseInt(parts[1]) * 60; 
    var seconds = parseInt(parts[2]); 

    return hoursAsSeconds + minAsSeconds + seconds; 
} 
+0

那個伎倆,謝謝! –