Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Format datetime in model in rails

I have a view which prints the date time as #{@event.starts_at.strftime("%m/%d/%Y %H:%M")}. So everytime I print starts_at, I have to use strftime in the view. I need to find a way to add a method to my 'event' model, so that the date gets formatted automatically everytime I print event.starts_at or event.method_name(starts_at)

like image 452
Vivek Tripathi Avatar asked Mar 17 '23 13:03

Vivek Tripathi

2 Answers

You can override the getter like follows:

class Event < ActiveRecord::Base
  def starts_at
    attributes['starts_at'].strftime("%m/%d/%Y %H:%M")

Take into account that you have to use a string and not a symbol for the attributes hash.

Said this, this locks you if your app tries to get internationalized, as time formats are different depending on the locales

You could use the rails I18n for it:


      default: '%A, %d. %B %Y, %H:%M Uhr'
      long: '%A, %d. %B %Y, %H:%M Uhr'
      short: '%d. %B, %H:%M Uhr'
      very_short: '%d.%m.%Y, %H:%M Uhr'

With that you could use:

> I18n.localize Event.first.starts_at, format: :very_short
# => "26.11.2012, 10:35 Uhr"

The localize method is aliased to I18n.l

and it will use the right one (if defined)

like image 108
Fer Avatar answered Mar 28 '23 04:03


You can add method, but it will pollute model with view related logic. Best way is to create decorator for this purposes, if you are new with decorators then you can add it to model.

def starts_at_format format = "%m/%d/%Y %H:%M"

Now you can use starts_at_format and it will automatically format the date

format has default value so if ever later need to use other format just pass the argument.

You can this use as:



   starts_at_format("%m %d %b") # define format
like image 37
Nermin Avatar answered Mar 28 '23 02:03