Reputation: 57
I made the following function to get the number of seconds from a time string.
function TimeStringToSeconds(TimeString){
var TotalTime = 0;
var SplitString = TimeString.toString().split(':');
TotalTime += parseInt(SplitString[0])*3600;
TotalTime += parseInt(SplitString[1])*60;
TotalTime += parseInt(SplitString[2]);
return TotalTime;
}
It works, but not if the input contains an 8 or an 9, example:
TimeStringToSeconds('00:01:00'); // Outputs 60
TimeStringToSeconds('00:02:00'); // Outputs 120
TimeStringToSeconds('00:08:00'); // Outputs 0 ???????
What am i doing wrong?
Upvotes: 1
Views: 85
Reputation: 32701
The problem is that a leading zero indicates octal notation. Use the following snippet:
parseInt(SplitString[0], 10)
This forces JavaScript to treat the number as decimal.
Upvotes: 2
Reputation: 138017
Always include the radix:
parseInt(SplitString[0], 10)
Without it, "08"
is parsed in octal base, with 8
being an invalid digit.
See also: parseInt at MDN
Upvotes: 4