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
Thanks,
Michael G.
On Oct 9, 2006, at 9:45 AM, Michael G. wrote:
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
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
On Mon, 9 Oct 2006, Michael G. wrote:
end
Michael G.
why are you using parse? without it your method is straightforward
enough:
harp:~ > cat a.rb
require “test/unit”
class Time
def begining_of_day
Time.mktime(year, month, day).send(gmt? ? :gmt : :localtime)
end
end
class TestBeginOfDay < Test::Unit::TestCase
def test_begin_of_day
start_of_day = Time.mktime 2006, 10, 1
time = Time.mktime 2006, 10, 1, 9, 45
assert_equal start_of_day, time.begining_of_day
end
end
harp:~ > ruby a.rb
Loaded suite a
Started
.
Finished in 0.000914 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
regards.
-a