[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Beginning of day given a Time value

Morton Goldberg

10/9/2006 2:16:00 PM

On Oct 9, 2006, at 9:45 AM, Michael Guterl wrote:

> Anyone have a nice idiomatic way given an instance of Time, to
> return the
> beginning of that day? Below is my approach but it just feels very
> wrong...
>
> require "test/unit"
> require "time"
>
> class Time
> def begin_of_day
> Time.parse "#{self.month}/#{self.day}/#{self.year}"
> end
> end
>
> class TestBeginOfDay < Test::Unit::TestCase
> def test_begin_of_day
> start_of_day = Time.parse "10/1/2006 00:00"
> time = Time.parse "10/1/2006 9:45"
> assert_equal(start_of_day, time.begin_of_day)
> end
> end

How about this?

class Time
def begin_of_day
self - 3600 * hour - 60 * min - sec
end
end

It passes your unit test.

Regards, Morton



1 Answer

Frederick Cheung

10/9/2006 2:34:00 PM

0


> How about this?
>
> class Time
> def begin_of_day
> self - 3600 * hour - 60 * min - sec
> end
> end
>
> It passes your unit test.

ActiveSupport has a beginning_of_day method which is basically
equivalent to that

This approach fails will fail if daylight saving changes in between
midnight and the object on which you are calling begin_of_day. For
example in the UK on the 29th of october midday is 13 hours after the
previous midnight.

Fred


--
Posted via http://www.ruby-....