1. Skip to navigation
  2. Skip to content

The ELC Community Blog

A knowledge exchange on Ruby on Rails and Agile Development


Readability Tips

by josh on October 28, 2007

From: fr.ivolo.us

Formatting Dates & Times

Coming from Java and other frameworks, the hardest part about Ruby on Rails can be finding the little things that make coding easier.

Here are some tips relating to dates and times:

>> @user.logged_in_at.strftime("Last login: %m/%d/%y at %I:%M %p")
#   => "Last login: 03/05/07 at 06:30 PM"

This can become:

>> @article.logged_in_at.to_s(:last_login)
#   => "Last login: 03/05/07 at 06:30 PM"

can be accomplished with:

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
  :last_login => "Last login: %m/%d/%y at %I:%M %p"
)

A little further:

>> @article.last_login
#   => "Last login: 03/05/07 at 06:30 PM"

with:

class Article < ActiveRecord::Base
  def last_login
    logged_in_at.to_s(:last_login)
  end
end

More with Date and Time

>> 1.year
=> 31557600
>> 1.year.ago
=> Fri Oct 27 18:10:01 -0700 2006
>> 2.years.from_now
=> Tue Oct 27 12:10:15 -0700 2009

And to make working with date ranges easier:

>> t = Time.now
=> Sun Oct 28 00:10:32 -0700 2007
>> (t.year-5..t.year+5).to_a
=> [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]

Or the same thing for your views:

select_year(Time.now)

Displays:

Comments

Will Sargent at 3:56 PM on October 28 2007

How would you remove the leading zero from the month in that example, that is, from 03/05/07 to just 3/5/07? I can’t find a way to do it.

Add a comment


home | services | Ruby on Rails Development | code | blog | company