Created_On and Updated_On

In Rails, for your model classes, if you add the fields created_on and updated_on (or created_at and updated_at), Rails automatically maintains the proper values for them. (On the database side, you need to create them as DATETIME fields.)

How cool is that! No longer do you need to manually track when users register, when moderators edit comments, etc.–Rails maintains all this information FOR you!

The only catch is printing them–by default, Rails prints them in a fairly ugly pattern, like this:

Sun Nov 04 12:56:00 -0500 2007

Note that it prints the day, the second, and even your time-zone difference! While useful, you probably don’t need all this information.

How, then, can you print them out nicely?

The asnwer is, like most programming languages, Ruby provides a method (called strftime) which formats dates, given a string with a particular syntax. For example, you could write:

self.created_on.strftime("%B %d, %Y")

And this would print “November 11, 2007″. Here are the list of tokens you can use for strftime:

  • %a – The abbreviated weekday name (eg. Sun)
  • %A – The full weekday name (eg. Sunday)
  • %b – The abbreviated month name (eg. Nov)
  • %B – The full month name (eg. January)
  • %d – Two-digit day of the month (eg. 07)
  • %H – Two-digit hour of the day, 24-hour clock (from 00 to 23)
  • %I – Two-digit hour of the day, 12-hour clock (from 01 to 12)
  • %j – Three-digit day of the year (from 001 to 366)
  • %m – Two-digit month of the year (from 01 to 12)
  • %M – Two-digit minute of the hour (from 00 to 59)
  • %p – Meridian indicator (AM or PM)
  • %S – Two-digit second of the minute (from 00 to 60)
  • %U – Two-digit week number of the current year, starting with the first Sunday as the first day of the first week (from 00 to 53)
  • %W – Two-digit week of the current year, starting with the first Monday as the first day of the first week (from 00 to 52)
  • %w – Day of the week (Sunday is 0; from 0 to 6 inclusively)
  • %y – Year without a century (from 00 to 99; eg. 00 for 2000, 47 for 2047)
  • %Y – Year with century (eg. 2007)
  • %Z – Time zone name
  • %% – Literal percent character

You can also find the same list here, too.

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , , , . Bookmark the permalink.