Rails Helper to Remove Leading Zero in 12 Hour Time Format

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)
  • Tim Shaffer

    You can also pass DATE_FORMATS a lambda (or anything else that responds to call). So you can do the following…

    Time::DATE_FORMATS[:pretty] = lambda { |time| time.strftime(“%a %b %d, %Y %I:%M%p”).gsub(/^0/,”).downcase }

    Then nothing needs to change in the view and you don’t need a helper. Just use to_s like normal:

    @post.created_at.to_s(:pretty)

  • http://kevinold.com Kevin

    Use %l (that’s a lower case “L”) for the hour and it’ll drop the zero.

    • pauly

      Thanks dude!!!!

    • http://twitter.com/stevemeisner Steve Meisner

      W00T!

    • http://communitypoint.ca/ Josh

      Nice one buddy! Why is this nowhere to be found in the docs?!