I have created a function to turn a 24 hour string aka “0800” or “2330” into minutes. Sometimes the strings will drop leading zeros so I need to account for this.
It works BUT to get the minute component I try get the last two characters of the string which, one would assume, would be this:
var timeString = "800"; //Can be "0800"
timeString.substring(timeString.length - 2, 2)
Which, if your string is “800” (leading zero dropped) then it would be the equivalent to
timeString.substring(3 - 2, 2)
However this returns nothing what so ever. I only get “00” (what I’m looking for) if I use the following code:
timeString.substring(timeString.length, 2)
To me this code is wrong but it works, somehow?
Can anyone explain why? Have I misunderstood how this function is meant to work?
The second parameter in the substring method isn’t the number of characters you want it is the index you want to go to. So right now you are going from substring(3-2, 2), index 2 to index 2, which gives you no characters.
Change it to: