Informatika Mihelac

Articles tagged with dates

December 16 2006 dates 0 comments

Working with dates in Ruby

Ruby has three classes for working with date and time: Date, DateTime which subclasses Date and Time. There is an interesting article why we need all 3 classes, and here are some notes about working with dates:

  • Time.now != DateTime.now && Time.superclass != Date
  • There is no method in Time class to convert object to a Date object, but you can write date = Date.new(time.year, time.mon, time.day). Rails extends DateTime and Time classes which allows to_date and to_time conversions for both classes.
  • Today is Date.today and now it is Time.now, there is no such thing as Date.now but there is Time.today (even I didn’t saw it in RDocs)
  • Tomorrow is Date.today+1, yestrday Date.today-1, to add or substract a month use Date.today >> 1 or Date.today << 1. See also Rails extensions to time class which allows to write things like Date.today.to_time.at_beginning_of_week
  • Date class includes Comparable module which allows us to write some_date.between?(Date.today, Date.today + 7)
  • Time.now.beginning_of_month.to_date.upto( Time.now.next_month.beginning_of_month.to_date-1) {|d| puts d.to_s} would print all days in current month in your Rails application.

Standard Ruby library also includes ParseDate library for parsing dates and returning array of values. Rails use ParseDate.parsedate to create dates so if you need to support input of additional date formats consider extending parsedate. I am not sure why Date.parse does not use ParseDate.parse but have its own implementation.

About

I am Bojan Mihelac and this blog is dedicated to share code, thoughts, tools and advices I came up with while working in Informatika Mihelac.

Contact: bmihelac@mihelac.org

RSS feedSubscribe to RSS Feed