From: Daniel Schierbeck Date: 2005-11-13T04:27:15+09:00 Subject: Re: Converting between Time and DateTime Lloyd Zusman wrote: > What is the recommended method for converting between Time objects and > those of type DateTime? > > I know that I can do this: > > dt = DateTime.new > t = Time.mktime(dt.year, dt.mon, dt.day, > dt.hour, dt.min, dt.sec) > > .. and this: > > t = Time.now > dt = DateTime.civil(t.year, t.mon, t.day, > t.hour, t.min, t.sec) > > However, this seems overly verbose to me, and I end up putting one or > both of the following into my ruby programs: > > class DateTime > def self.fromTime(t) > return DateTime.civil(t.year, t.mon, t.day, > t.hour, t.min, t.sec) > end > end > > class Time > def self.fromDateTime(dt) > return Time.mktime(dt.year, dt.mon, dt.day, > dt.hour, dt.min, dt.sec) > end > end > > Is there any reason for why we can't have similar methods as part of the > official DateTime and Time classes? > > Or is there already some sort of mechanism for this that I have > overlooked? > > Thanks in advance. > > I think this would be more Rubyish: class DateTime def to_time Time.mktime(year, mon, day, hour, min, sec) end end class Time def to_datetime DateTime.civil(year, mon, day, hour, min, sec) end end I haven't tested it, but it should work. Cheers, Daniel