# Shouldn't ranges work for datetime fields

**URL:** <https://www.ruby-forum.com/t/shouldnt-ranges-work-for-datetime-fields/75037>\
**Category:** Rails\
**Created:** [November 7, 2006, 11:07am UTC](https://www.ruby-forum.com/t/shouldnt-ranges-work-for-datetime-fields/75037 "2006-11-07T11:07:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bjhess](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ce7236/32.png) [@bjhess](https://www.ruby-forum.com/u/bjhess)\
**Post date:** [November 7, 2006, 11:07am UTC](https://www.ruby-forum.com/t/shouldnt-ranges-work-for-datetime-fields/75037/1 "2006-11-07T11:07:15Z")

</div>

I figure ranges should work just fine for a datetime. I want to weight  
a total based on how recently an item was created. Using the case  
statement, I check various ranges. I simply cannot get this to work:

```
    weighted_total +=
      case item.created_at
        when Time.now...24.hours.ago: 20
        when 24.hours.ago...48.hours.ago: 8
        when 48.hours.ago...1.week.ago: 4
        when 1.week.ago...2.weeks.ago: 2
        when 2.weeks.ago...4.weeks.ago: 1
        else 0
      end

```

Every “created\_at” field resolve to the else case.

I also tried it with if statements and Time.now…24.hours.ago ===  
item.created at boolean expressions. In that case, every single if  
statement was successful, regardless of the range.

I’m sure I’m simply missing some intricacy with date handling. Every  
language seems to have its gotchas in this realm.

---

<div class="post-metadata">

**Author:** ![bjhess](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ce7236/32.png) [@bjhess](https://www.ruby-forum.com/u/bjhess)\
**Post date:** [November 7, 2006, 11:07am UTC](https://www.ruby-forum.com/t/shouldnt-ranges-work-for-datetime-fields/75037/2 "2006-11-07T11:07:23Z")

</div>

bjhess wrote:

> ```
> when 2.weeks.ago...4.weeks.ago: 1
> 
> ```
> 
> language seems to have its gotchas in this realm.  
> Try reversing the order of your ranges so that the oldest time is  
> defined first…

case item.created\_at  
when 24.hours.ago … Time.now: 20  
when 48.hours.ago … 24.hours.ago: 4  
…  
end

\_Kevin

---

<div class="post-metadata">

**Author:** ![bjhess](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ce7236/32.png) [@bjhess](https://www.ruby-forum.com/u/bjhess)\
**Post date:** [November 7, 2006, 11:07am UTC](https://www.ruby-forum.com/t/shouldnt-ranges-work-for-datetime-fields/75037/3 "2006-11-07T11:07:44Z")

</div>

Thanks, \_Kevin. You’re a life saver!
