VocabReminder
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
VocabQuiz
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app

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)

Tagged w/ #12 hour time #datetime #helpers #initializers #leading zero #strftimeruby on rails