Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `from_now` wrong when called on a Fixnum?

I need to store some time periods in a yaml file, like this:

test:
testing: <%= 1.month %>

I grab the data in an initializer like this:

Class::TIMES = YAML.load(ERB.new(File.new(Rails.root.join('config', 'times.yml')).read).result)

So far so good. But the times I get from this are always off by a day; testing shows this. For example:

<Tue, 06 Mar 2012> expected but was <Wed, 07 Mar 2012>.

The test line:

assert_equal 1.month.from_now.to_date, @object.finished_at.to_date

Elsewhere, @object's finished_at is set like this:

# duration is from the YAML file
self.finished_at = duration.from_now

It always seems to be off by a day, no matter what time period I put in the YAML file. Why does this happen?

EDIT: This seems to be an issue with Fixnums and from_now:

> 1.month.from_now
 => Tue, 06 Mar 2012 21:05:00 UTC +00:00 

> 1.month.to_i.from_now
 => Wed, 07 Mar 2012 21:05:05 UTC +00:00
like image 733
Kevin Griffin Avatar asked Mar 15 '26 13:03

Kevin Griffin


1 Answers

When you convert 1.month to an integer it arbitrary sets the duration getting passed into from_now to 2592000 seconds i.e 30 days regardless of what month it is.

I ran into this issue once before. Check out the documentation for the Data and Time Helper Methods .

While these methods provide precise calculation when used as in the examples above(".. 1.month.from_now .."), care should be taken to note that this is not true if the result of months’,years’, etc is converted before use

like image 188
ashoda Avatar answered Mar 18 '26 03:03

ashoda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!