From: Rick DeNatale Date: 2010-02-10T04:12:02+09:00 Subject: Re: [Q] algorithm to truncate date to beginning of week? On Tue, Feb 9, 2010 at 1: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. No, actually ActiveSupport defines the week to start on Monday, which is the ISO 8601 definition, not Sunday. To get the beginning of a Sunday starting week using ActiveSupport, you could use Time.now.end_of_week.beginning_of_day This will get the end of the next Sunday on or after the time in question, and then adjust to the beginning of the day. Approaches like Time.now.beginning_of_week - 1.day will fail on Sundays, you'll get the previous Sunday instead. -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale