Stop Looking up strftime Codes!

When reading code that formats dates and times, I’ve never managed to rememeber the strftime codes. It’s gibberish. Before I worked with Ruby, I worked with Lasso, and both allow the simple creation of custom methods which allowed me to express time the way I wanted. Like this:

  • member_birthdate.as_iso_date = 1955-06-30
  • member_birthdate.as_moYYYY = Jun 1953
  • member_birthdate.as_moDDYYYY = Jun 30, 1953
  • member_birthdate.as_monthDDYYYY = June 30, 1953

The pattern is pretty simple. Most methods use the DD and YY or YYYY as expected. I opted to use mo to mean short months and month to mean full months. I admit my choice of iso_date might be inconsistent, but I’ve always called the YYYY-DD-MM format the ISO date.

I also have methods for things like:

  • some_date.from_string converts various strings to a Time class
  • some_date.add_days(8)
  • some_date.subtract_weeks(6)
  • some_date.as_days_since(another_date)
  • some_date.days_elapsed implies time elapsed from that date till now

Many of these are available with a number of different intervals like years, months, quarters, weeks, days, hours, etc.

The from_string method converts strings like these:

  • Dec 25 2001
  • 25 Dec 2001
  • 2001 Dec 25
  • 2001 25 Dec
  • Dec 12 01
  • Dec 25
  • 25 Dec
  • 2001-25-12
  • 2001/12/25
  • 2001 12, 25
  • 25-12-2001
  • 25-12-01
  • 25-12-99
  • 12-25-01
  • 12-25-2001

There’s a flag allowing the ambiguous dates to be interpreted as :usa or :euro formats.

I also have a Rails helper for handling dates and times when they could be empty or null.

You’ll find both attached to this article as downloads. I actually have these and many other convenience methods wrapped up as private gems for my projects. One of these days I’ll get around to releasing them. Meanwhile, maybe these files are useful as is, or give you some ideas for your own take on the idea.


Download (5.8 KB) :

Extensions to Ruby Date and Time classes for more expressive code.

Download (1.1 KB) :

Rails helper for handling Dates and Times more expressively.