Jul 24 2006

Ruby Time Formatting

The Time class in Ruby has a powerful formatting function which can help you represent the time in a variety of ways. The strftime function is modeled after C’s printf. Here are some usages examples:

t = Time.now
t.strftime("%m/%d/%Y %H:%M:%S") # 07/24/2006 09:09:03

t.strtime("%A") # Monday
t.strftime("%B") # July

You can use the lower case a and b to get the abbreviated name of the weekday and month, respectively. To get the the day of the year, between 1 – 366, use the j option.

t.strftime("%j") # 205

The strftime function is useful when formatting the created_at datetime of your Rails application ActiveRecord models.