Skip to content

Ruby Time Functions Rock!!

I haven’t had much cause to play with the Time module in Ruby until today. I have used Time.now quite a bit, but not too much more than that. However, today I had to find the last 6 months names to label a graph and in a short period of time I had come up with this:

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
labels = []
0.upto(5) do |x|
  labels.unshift(months[Time.now.months_ago(x).month-1])
end

Which I think is pretty neat, especially remembering what a pain it was in Perl last time I had to do it……..

5 Comments

  1. Mully wrote:

    You may already know this, but you could replace your own array of month abbreviations with the Date module’s ABBR_MONTHNAMES constant…

    require ‘date’
    months = Date::ABBR_MONTHNAMES

    The first element is ‘nil’, resulting in the index matching the month numbers (1 = ‘Jan’, etc.). I frequently work with this array and have found this constant handy.

    Sunday, February 4, 2007 at 5:24 am | Permalink
  2. Scott Rutherford wrote:

    Hi Mully, cheers for that. I have to admit I didn’t know, but I do now. That makes it even neater:

    <pre>
    labels = []
    0.upto(5) do |x|
    labels.unshift(Date::ABBR_MONTHNAMES[Time.now.months_ago(x).month])
    end
    </pre>

    Thanks, Scott.

    Sunday, February 4, 2007 at 5:24 am | Permalink
  3. Blake wrote:

    http://chronic.rubyforge.org/

    I’ve been using this to spice time handling up a bit. Pretty cool stuff.

    Sunday, February 4, 2007 at 5:24 am | Permalink
  4. Scott Rutherford wrote:

    Hi Blake, Yep I’ve had a little play with chronic, seems to be great with certain stuff (‘in an hour’, ‘yesterday’, etc) but not so good for things like ‘the first day of next month’, ‘the first day of last month’. But still a great idea. I need to use it more to understand how to get the best out of it I think.

    Cheers
    Scott.

    Sunday, February 4, 2007 at 5:24 am | Permalink
  5. Erik Kastner wrote:

    Hey, you are sitting next to me at FoWA. Here’s a more idiomatic way of doing the same thing:
    (0..5).collect {|months_ago| Time.now.months_ago(months_ago).strftime("%b") }.reverse

    Sunday, February 4, 2007 at 5:24 am | Permalink