Heading image for post: Better Date and Time Formatting for Ruby


Better Date and Time Formatting for Ruby

Profile picture of Dave Lyon

While working with dates and times in a Rails app recently, my pair and I found myself having to deal with some really annoying padding issues. We wanted to output times like "8:00pm" using strftime and found that with single digit hours, what we got was " 8:00pm."

Initially, we thought the simplest thing to do was to 'strip' the string, but after looking at the documentation for Time#strftime we noticed some extra flags that could be passed to control the padding of interpreted formats.

-  don't pad a numerical output.
_  use spaces for padding.
0  use zeros for padding.

Super useful! Here's some examples:

date = Date.new(2012,1,1) 

date.strftime("%m") # => "01"

date.strftime("%-m") #=> "1"

date.strftime("%_m") #=> " 1"

More posts about Development Ruby