时间计算器给出错误答案
time-to calculator giving wrong answer
所以我做了一个函数来确定我要等多久才能到达公交车:
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");
但它给了我错误的答案....
有些计算肯定是错误的,但我这辈子都想不出来!
我在这里发现的一个问题是您的 toSeconds 函数,它没有将所有秒数相加,而是将秒数连接为一个字符串。给定您的示例 (16:30:00),当您应该返回 57600 + 1800 + 00 = 59400 秒时,您将返回 57600180000 秒。
试试这个方法,看看它是否能让你更接近解决方案post如果你有其他问题,请发表评论。
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;
}
所以我做了一个函数来确定我要等多久才能到达公交车:
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");
但它给了我错误的答案.... 有些计算肯定是错误的,但我这辈子都想不出来!
我在这里发现的一个问题是您的 toSeconds 函数,它没有将所有秒数相加,而是将秒数连接为一个字符串。给定您的示例 (16:30:00),当您应该返回 57600 + 1800 + 00 = 59400 秒时,您将返回 57600180000 秒。
试试这个方法,看看它是否能让你更接近解决方案post如果你有其他问题,请发表评论。
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;
}