[#3006] CVS repository — "Eugene Scripnik" <hoaz@...>

Hello.

21 messages 2004/06/16
[#3008] Re: CVS repository — ts <decoux@...> 2004/06/16

>>>>> "E" == Eugene Scripnik <hoaz@gala.net> writes:

[#3009] Re: CVS repository — Michal Rokos <michal@...> 2004/06/16

Hi!

[#3057] Ruby 1.8.2 to be released. — matz@... (Yukihiro Matsumoto)

Hi,

20 messages 2004/06/23

Re: Date.from_time

From: Gavin Sinclair <gsinclair@...>
Date: 2004-06-14 12:06:20 UTC
List: ruby-core #2984
On Monday, June 14, 2004, 7:19:59 PM, nobu wrote:

> Hi,

> At Sun, 13 Jun 2004 12:29:17 +0900,
> Daniel Berger wrote in [ruby-core:02979]:
>> t = Time.new
>> d = Date.new(*ParseDate.parsedate(t.to_s)[0..2])

> $ ruby -rdate -e 'puts Date.new(*Time.now.to_a.values_at(5,4,3))'
> 2004-06-14

So it could be as simple as the following:

  class Date
    def Date.from_time(time)
      Date.new(*time.to_a.values_at(5,4,3))
    end
  end

  class DateTime
      #
      # This is more complicated because Time and DateTime handle
      # timezones in *very* different ways.  Time deals in seconds,
      # DateTime deals in a Rational part of a day.  DateTime also
      # gives you a *different* time when you specify the time zone,
      # which can't be specified up front.
      #
      # This implementation honors the timezone information from the
      # Time object, but not the sub-second resolution, unfortunately.
      # DateTime can *return* such a value with #sec_fraction, but
      # I can't see how to *set* that value.
      #
    def DateTime.from_time(time)
      gmt_offset = time.gmt_offset                     # in seconds
      datetime_offset = Rational(gmt_offset, 24*3600)  # as part of a day
      args = time.to_a[0..5].reverse << datetime_offset
      DateTime.new(*args)
    end
  end

The above implementation seems to work.  Of course, scrutiny and unit
tests will make sure of it.  I'm going to use it in my code, anyway.

So is there any hope of getting these methods in the standard library
once their implementation has been found to be correct?
  
BTW, the fact that Time#gmtime modifies the receiver bothers me.  Why
can't we have 'gmtime' and 'gmtime!', rather than 'getgm' and 'gmtime'?

Gavin




In This Thread

Prev Next