A pet peeve of mine is the lack of a documented shortcut in Ruby’s #strftime to function to return the hour of the day, in twelve-hour clock, without a leading zero. To wit:
puts Time.now.strftime("%I:%M") # >> 03:29
That’s not particularly attractive. I could strip the leading zero with some string manipulation, but this is getting sledgehammer-ish to crack a nut. Fortunately, this works:
puts Time.now.strftime("%l:%M") # >> 3:29
That’s a lowercase L in the formatting string, which returns the number of hours in a twelve-hour clock sans leading zero. Result! And yes, that’s undocumented everywhere I’ve looked. Thanks to my colleague Colin for pointing that trick out.
Now, if only I could get it to return am/pm without having to call #downcase
Paul Mison said... 1
I’d expect that Ruby’s strftime just passes things straight down to the underlying C strftime library:
blech@theproject:~/web/husk.org/misc$ man strftime
…
%l Hour (12-hour clock) [1,12]; single digits are preceded by a blank.
Also:
%p Locale’s equivalent of either a.m. or p.m.
I’m not sure if that’s lower case by default in any English locale, though. Personally I like leading zeroes and the twentyfour hour clock.
Tom Ward said... 2
Nice find. Just what I was looking for. Cheers Tom.