SQLTerminal.app
now available

XPath.app
now available
Want fresh tech tips in your inbox?

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

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
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