Jeremy Hinegardner
10/27/2006 6:23:00 AM
On Fri, Oct 27, 2006 at 12:50:03PM +0900, ara.t.howard@noaa.gov wrote:
> On Fri, 27 Oct 2006, _Kevin wrote:
>
> >
> >List Recv wrote:
> >>Related question:
> >>
> >>Is there a way to convert a Time (or DateTime) to Ruby's Date class?
> >
> >I added a few conversion methods like this to 'ruby-units' gem
> >
> >class Time
> >def to_datetime
> > DateTime.civil(1970,1,1)+(self.to_f+self.gmt_offset)/86400
> > end
> >
> > def to_date
> > Date.civil(1970,1,1)+(self.to_f+self.gmt_offset)/86400
> > end
> >end
> >
> >This seems to work pretty well, although I haven't tested it on a wide
> >range of OSs.
>
> it's nice to have
>
> Time.to_time
> Time.to_date
>
> Date.to_time
> Date.to_date
>
> DateTime.to_time
> DateTime.to_date
>
> so you can do
>
> do_not_care_which_one.to_time
> do_not_care_which_one.to_date
>
> a la rails.
>
> 2 cts.
And that's why we have facets!
% gem install facets
% cat date-time.rb
require 'date'
require 'rubygems'
require 'facets'
require 'date/to_time'
require 'date/to_date'
require 'time/to_date'
require 'time/to_time'
timers = {
:date => Date.today,
:time => Time.now,
:date_time => DateTime.now
}
["to_date", "to_time"].each do |method|
timers.each_pair do |name,time|
result = time.send(method)
class_name = result.class.name
puts "#{name.to_s.rjust(10)}.#{method} yields result #{result} with class of #{class_name}"
end
end
puts
puts "superclass of DateTime : #{DateTime.superclass}"
% ruby date-time.rb
date.to_date yields result 2006-10-27 with class of Date
time.to_date yields result 2006-10-27 with class of Date
date_time.to_date yields result 2006-10-27T00:18:27-0600 with class of DateTime
date.to_time yields result Fri Oct 27 00:00:00 -0600 2006 with class of Time
time.to_time yields result Fri Oct 27 00:18:27 -0600 2006 with class of Time
date_time.to_time yields result Fri Oct 27 00:00:00 -0600 2006 with class of Time
superclass of DateTime : Date
When to_date is called on an instance of DateTime its still calling it
on Date object since DateTime.superclass == Date. So anywhere a Date is
used, a DateTime can be used.
enjoy,
-jeremy
--
========================================================================
Jeremy Hinegardner jeremy@hinegardner.org