Written by Sean Behan on Sun Jun 17th 2012

I can't find a strftime() format that will output the hour without the leading zero. For instance 6:20 will be instead 06:20. This just looks a little sloppy. I created a datetime.rb intializer which will contain custom datetime formats for my application.

# RAILS_ROOT/config/initializers/datetime.rb
Time::DATE_FORMATS[:date] = "%a %b %d, %Y"
Time::DATE_FORMATS[:time] = "%I:%M%p"
# ...
Next I set up a helper function which will string together the :date and :time formats and remove the leading zero in the hour with the .gsub method on the string.
  # RAILS_ROOT/app/helpers/application_helper.rb
  def fulltime(created_at)
    created_at.to_s(:date)+" "+created_at.to_s(:time).gsub(/^0/,'').downcase
  end
In a view I'll just pass the timestamp to the fulltime function
fulltime(@post.created_at)

Tagged with..
#12 hour time #datetime #helpers #initializers #leading zero #strftime #Ruby on Rails

Just finishing up brewing up some fresh ground comments...