From: Chuck Remes on

On Feb 9, 2010, at 12:53 PM, Gary Wright wrote:

>
> On Feb 9, 2010, at 1:32 PM, Chuck Remes wrote:
>
>> I need to be able to take any date after Jan 1, 1980 and truncate it to the nearest week.
>>
>> Example:
>>
>> Wed Jan 09 17:53:23 -0600 1980 should truncate to Sun Jan 06 00:00:00 -0600 1980
>>
>> Tue Feb 09 12:29:51 -0600 2010 should truncate to Sun Feb 07 00:00:00 -0600 2010
>>
>> I've tried all sorts of tricks with modulus (% operator) on the integer representation of time but I can't get anything to work over a range of dates.
>>
>> Anyone have any bright ideas?
>
>>> require 'active_support'
> => true
>>> Time.now.beginning_of_week
> => Mon Feb 08 00:00:00 -0500 2010
>>>
>
> It also looks like midnight is considered part of the next day not the previous day as in your example.

Ooh, all of ActiveSupport for a little date manipulation? Nail, meet hammer!

Thanks for this suggestion. I'm going to go with using Date#wday to calculate it though.

cr


From: Gary Wright on

On Feb 9, 2010, at 2:22 PM, Chuck Remes wrote:
>
> Ooh, all of ActiveSupport for a little date manipulation? Nail, meet hammer!

Of course reinventing the wheel isn't necessarily a good thing either.

Here is another approach:

>> require 'chronic'
=> true
>> Time.now
=> Tue Feb 09 15:31:25 -0500 2010
>> Chronic.parse 'midnight last saturday'
=> Sun Feb 07 00:00:00 -0500 2010
>> Chronic.parse 'midnight last saturday', :now => Date.parse('12/25/2010')
=> Sun Dec 19 00:00:00 -0500 2010