On Sunday I looked at how to pad a number with leading zeroes in Javascript and in this post look at a simpler function to pad a number to just two digits as if required for days and months, and hours, minutes and seconds.
Please note: this doesn't work for negative numbers; it was designed specifically for padding with leading a zeros a number which will be used in date formats where negatives are not possible (there will be a post later this week about this). I'll write another post to revise what's here and will work with negative numbers.
Check out the original pad function in the previous post to see how to pad a number to any number of places. The following "pad2" function only ever pads the number to two places adding a leading zero if necessary. This makes it suitable for ensuring dates (days and months) and times (hours, minutes and seconds) are always two digits.
Some code to test the above:
And the resulting output:
The reason I needed to pad numbers was for formatting dates and times in a text field in a web form for sending through to a database. I'll show how to use the Javascript Date object to return the current date and time in a database ready format in my next Javascript post
In my original post the return value type would be either a string or an integer depending if the value passed in was a single digit or double digit. Hans' modification ensures a string type is always returned.
0 comments:
Post a Comment