2016-09-23 109 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

那个伎俩,谢谢! –