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
Timeclass to convert object to aDateobject, but you can writedate = Date.new(time.year, time.mon, time.day). Rails extendsDateTimeandTimeclasses which allowsto_dateandto_timeconversions for both classes. - Today is
Date.todayand now it isTime.now, there is no such thing asDate.nowbut there isTime.today(even I didn’t saw it in RDocs) - Tomorrow is
Date.today+1, yestrdayDate.today-1, to add or substract a month useDate.today >> 1orDate.today << 1. See also Rails extensions to time class which allows to write things likeDate.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.
I am Bojan Mihelac and this blog is dedicated to share code, thoughts, tools and advices I came up with while working in
Speak your mind: