ruby Date, DateTime to Time conversion

Sometimes I needed to convert a Date or a DateTime object to it’s Time-class equivalent.

Note that Date can be converted to Time without loosing “a lot of information”.

However, in a lot of cases we do not care about these details – we just need a method that conversion.

You can paste the following snippet in your ruby-code – tested with ruby 1.8.7 (2010-08-16 patchlevel 302)

class Date
  def to_time    
    usec = self.respond_to?("sec_fraction")? (self.sec_fraction * 60 * 60 * 24 * (10**6)).to_i : nil    
    h = self.respond_to?("hour")? self.hour : nil
    m = self.respond_to?("min")? self.min : nil
    s = self.respond_to?("sec")? self.sec : nil
    Time.local(self.year, self.month, self.day, h, m, s, usec)
  end
end

This enables you to write:
Date.today.to_time
DateTime.now.to_time

Leave a Reply

Your email address will not be published. Required fields are marked *