Tuesday, December 11, 2012
Remove Leading Zero on strftime function
strftime is one of Ruby DateTime function that will enable you to formats date according to directives of given format String. This function , according to the documentation, existed since Ruby 1.8.6. And this function still existed on Ruby latest stable version : 1.9.3. As you can see on the documenation (or you may already have used it), the directives for Hour, Month and others will add leading zero to the result. For example, if you use :
strftime('%I') #Hour of the day, 12-hour clock (01..12)
You'll get 01,02,03,..12 (depending on the DateTime you passed). How to get 1,2,3,4,..12 (without leading zero) ?
It's true if you need to get day of the Month without leading zero, you can use %e (as mentioned on the documentation, instead of using %d). Unfortunately, I can't find such function to get Hours without leading zero. Therefore, after doing a little experiment, I found that adding a - after % will remove leading zero.
strftime('%-I') #Hour of the day, 12-hour clock (1..12) - without leading zero strftime('%-H') #Hour of the day, 24-hour clock (1..24) - without leading zero
So, we don't need to develop our own function just to format date or time without leading zero.