Ruby strftime in UK format i.e. dd/mm/yy

1.1k Views Asked by At

I know I can do @something.created_at.strftime('%d/%m/%y') to get the date in dd/mm/yy format, but it's a pain.

American users however just need to do a simple: @something.created_at.strftime('%x'), which gives mm/dd/yy.

Is it possible to rig %x to work the proper way, i.e. the British way (since we invented time).

3

There are 3 best solutions below

1
On BEST ANSWER

The correct way of doing this now is:

# in config/locales/en.yml
date:
  formats:
    default:
      "%d/%m/%y"

Then in the view:

= l Date.current

Yep, that's it. The l method is shorthand for I18n.localize. Read more in the Rails I18n guide.

0
On

If this is something you are going to use often you could use a Proc:

def brit_date
  Proc.new 
end

proc = brit_date {Time.now.strftime("%d/%m/%y")}
proc.call
 => "24/11/14"
0
On

Have look at easy_dates gem

gem install gemcutter
gem tumble
gem install easy_dates

you don't have to worry about formatting your dates continually with strftime.