From: Daniel Schierbeck Date: 2005-11-14T02:42:15+09:00 Subject: Re: Converting between Time and DateTime Lloyd Zusman wrote: > Daniel Schierbeck writes: > >> Lloyd Zusman wrote: >>> Daniel Schierbeck writes: >>> >>>> [ ... ] >>>> >>>> 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. >>> Thanks. Is this considered more ruby-ish because of the non-camel-case >>> of the method names? ... or because of the to_* methods instead of the >>> from* constructors? ... or both? >>> >> Both. It also allows you to do something like this: >> >> def some_time_method(time) >> time = time.to_time # now we know we have a Time object >> end >> >> some_time_method(DateTime.new(...)) >> >> That way you can use a DateTime object instead of a Time object and have >> it automatically converted. Otherwise, you'd have to do this: >> >> some_time_method(Time.from_datetime(DateTime.new(...))) > > Got it. Thanks! > > So now, all we need is to have a few to_* conversion methods added to > the standard Time, DateTime, and Date classes so that we all don't have > to keep re-inventing this. :) > > Yeah, but only if there's a strong enough sentiment in the community. No reason to add to the standard library unless the functionality is really needed. Cheers, Daniel