jQuery Question

# time-to calculator giving wrong answer

So i made a function to determine how long i have to wait until the buss arrives:

``````function arrival(arrtime){

//convert to seconds
function toSeconds(time_str) {
// Extract hours, minutes and seconds
var parts = time_str.split(':');
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");
``````

but it's giving me the wrong answer....
some calculations must be wrong but for the life of me i can't figure it out!

One issue I have found here is your toSeconds function, instead of adding up all the second it is concatenating the seconds as a String. Given your example (16:30:00) you are returning 57600180000 seconds when you should be returning 57600 + 1800 + 00 = 59400 seconds.

Try this method and see if it gets you closer to a solution post a comment if you have other issues.

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