Re: Duration

Frederick Cheung
Wed, 22 Dec 2010 13:03:35 -0000

On Dec 22, 6:41 am, Jack Waugh
<7aq3z2h...-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:
> "Just specify units and you''ll be fine."
>
> That appeals to my notion of what is logical.  Let''s try it.
>
> >> x = DateTime.now
>
> => Wed, 22 Dec 2010 01:30:36 -0500>> y = x + 1.day
>
> => Thu, 23 Dec 2010 01:30:36 -0500
>
> So far, so good.
>
> >> (y - x) / 1.second
>
> => Rational(28799745541, 28800000000)
>
> Since y is one day later than x, y - x should be a day.  Dividing that by 1
> second should yield a pure number equal to the number of seconds in a day.
>
The problem here is that y-x is a unitless number. Even if someone had
thought to override / for datetime or durations (they haven''t) you
can''t know that this is a number that has come from subtracting two
datetimes, two dates, two times or something completely different

> >> ((y - x) / 1.second).to_i
>
> => 0
>
> Even if coerced to an integer, the number of seconds in a day should be
much
> more than zero.
>
> I used units, but the result differs from what seems to me to make sense.
> How can I safely represent a duration in the database and then use the
> duration in date arithmetic?

When you subtract or divide datetime objects you get unitless
Rationals - the rest of the code doesn''t know if that''s a
number of
seconds, days, years etc. ActiveSupport::Duration assumes seconds
which happens to be wrong. If you used Time instead of DateTime I
think things would work as you expect. If that''s not an option, I
can''t think of a really nice way of handling this short of adding
quite a lot of extra stuff to DateTime /  wrapping DateTime in
something else or just being really meticulous about always being very
aware that some numbers are numbers of days and others numbers of
seconds. Even then I think you could always find some operation
(squareroot, gamma function, whatever) that exposed that something was
thinking in days and the other was thinking in seconds.

Fred