19

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.

Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131

1 Answers1

43
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.

Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
  • Wish every solution was this simple and straightforward. +1 – flarn2006 Aug 15 '16 at 06:46
  • This solution might work only on Unix systems, not on Windows. [This answer to “Python `strftime` – date without leading 0?”](https://stackoverflow.com/a/2073189/578288) is about the same task in Python, and says that `%-` only works on Unix. [Why does “%-d”, or “%-e” remove the leading space or zero?](https://stackoverflow.com/q/28894172/578288) says that the incompatibility is because Python calls the underlying operator system’s `strftime`, which may have platform-specific extensions. I don’t know if Ruby’s `strftime` is the same. – Rory O'Kane Aug 10 '17 at 22:38