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.
ISO 8601 specifies that all times shall have a leading zero (though durations may omit it). So, as part of conforming to the ISO 8601 standard, Stack Overflow should show leading zeros for hours before 10 am. e.g.
Your answerIf you add a hyphen between the % and the letter, you can remove the leading zero. For example %Y/%-m/%-d. This only works on Unix (Linux, OS X), not Windows. On Windows, you would use #, e.g. %Y/%#m/%#d.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With