Scott Rutherford

Life on and off the Rails

 

Ruby Time Functions Rock!!

February 4th, 2007

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 Responses to “Ruby Time Functions Rock!!”

  1. Mully Says:
    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.
  2. Scott Rutherford Says:
    Hi Mully, cheers for that. I have to admit I didn't know, but I do now. That makes it even neater:
    labels = []
    0.upto(5) do |x|   
      labels.unshift(Date::ABBR_MONTHNAMES[Time.now.months_ago(x).month])
    end
    
    Thanks, Scott.
  3. Blake Says:
    http://chronic.rubyforge.org/ I've been using this to spice time handling up a bit. Pretty cool stuff.
  4. Scott Rutherford Says:
    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.
  5. Erik Kastner Says:
    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
Leave a Reply

This blog used the Shay theme as a base and is powered by Mephisto