Question

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.

Was it helpful?

Solution

Time.now.strftime '%a %-l:%M %p' #=> "Thu 1:51 PM"

Write %-l instead of %l. The - strips leading spaces and zeroes.

You can use - with the other format codes, too. The Ruby strftime documentation even mentions %-m and %-d, though it fails to mention that you can use - with any code. Thus, %-I would give the same result as %-l. But I recommend %-l, because using l instead of I signifies 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 strftime format codes, including ones with - and the similar syntaxes _ and 0. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top