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

5 comments on this entry.

  • Paul Mison | 27 Nov 2007

    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.


    %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 | 14 Dec 2007

    Nice find. Just what I was looking for. Cheers Tom.

  • Phil | 6 May 2009

    Lower case am/pm is achieved with %P.
    Yup, that’s right – an upper case ‘P’. Go figure!

  • Mabed | 16 Sep 2009

    Cool, unfortunately, it doesn’t work if I have an expression where I started with a number of seconds for example if I stated with 10000 seconds.

    time = Time.at(10000).gmtime.strftime(“”%l:%M””) => 2:46 which is incorrect. I was hoping it would output: 2:46:40

  • Mabed | 16 Sep 2009

    In case anybody looks for the solution to a problem like mine, please take a look at