excpt / moments

Handles time differences and calculations.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Precision?

joshuapinter opened this issue · comments

Hey There,

Coming over here as a possible replacement for TimeDifference but saw that the precision in (at least) in_minutes was being rounded off. For example:

irb(main):001:0> t1 = 14.days.ago
=> Thu, 04 Aug 2022 15:52:25 MDT -06:00
irb(main):002:0> t2 = Time.zone.now
=> Thu, 18 Aug 2022 15:52:31 MDT -06:00
irb(main):004:0> TimeDifference.between( t1, t2 ).in_minutes
=> 20160.09

irb(main):008:0> Moments.difference( t1, t2 ).in_minutes
=> 20160

Is there an option or something to keep the fractional precision?

To get all the detail time differences I recommend using .to_hash. It'll provide you with a hash with all the info in it.

{ years: 5, months: 7, days: 5, hours: 19, minutes: 29, seconds: 6 }

Another option would be to extend the api to allow .in_minutes and all the other methods to accept some value like :precise as parameter to return the raw untouched result.

Thanks for the quick reply @excpt! I agree, I think a :precise option or something would be ideal. The hash is nice but not what we're after. We need to use this difference in a rate calculation and therefore can't afford the inaccuracy introduced with rounding things off.

How difficult do you think that would be to implement?

Let me know. Thanks!

I'll look into it this week. This shouldn't be too hard to implement.

Beauty.

Please checkout the https://github.com/excpt/moments/tree/feature/precision-option branch.

Usage:

diff = Moments.difference(from, to, :precise)

puts diff.in_minutes
puts diff.in_hours
puts diff.in_days
puts diff.in_weeks

Nice job! Looks good - in fact, even more precise than the outgoing TimeDifference:

t1 = 14.days.ago
#=> Tue, 23 Aug 2022 13:53:35.570068000 MDT -06:00
t2 = Time.zone.now
#=> Tue, 06 Sep 2022 13:53:39.148204000 MDT -06:00
TimeDifference.between( t1, t2 ).in_minutes
#=> 20160.06
Moments.difference( t1, t2 ).in_minutes
#=> 20160
Moments.difference( t1, t2, :precise ).in_minutes
#=> 20160.066666666666

hi - we're in the exact same situation, migrating from TimeDifference. The solution on the branch sounds perfect; are there plans to merge it in?

Thanks for maintaining this gem!

Yeah, would be nice to get this merged in. We've been using the feature branch in Production for a couple months without issue.

Merged #12.

I will release a new version this weekend.

Thanks for all your patience. :)

🚀 🙏

Fixed in #12.