In a Ruby 1.9 program, I want to format the current time like Thu 1:51 PM. What format code should I use for the hour of the day (1 in this example)?
Time.now.strftime '%a %I:%M %p' #=> "Thu 01:51 PM"
Time.now.strftime '%a %l:%M %p' #=> "Thu 1:51 PM"
%I has a leading zero (01). %l has a leading space ( 1). I don’t see any other format code for the hour in the strftime documentation. I can’t use .lstrip because the space is in the middle of the string. I could use .gsub(/ +/, " "), but I’m wondering if there’s a less hacky, simpler way.
Write
%-linstead of%l. The-strips leading spaces and zeroes.You can use
-with the other format codes, too. The Ruby strftime documentation even mentions%-mand%-d, though it fails to mention that you can use-with any code. Thus,%-Iwould give the same result as%-l. But I recommend%-l, because usinglinstead ofIsignifies to me that that you don’t want anything at the beginning – the space it writes looks more accidental.You can also see an exhaustive list of Ruby 1.8
strftimeformat codes, including ones with-and the similar syntaxes_and0. It says that Ruby 1.8 on Mac OS X doesn’t support those extended syntaxes, but don’t worry: they work in Ruby 1.9 on my OS X machine.