Reputation: 26192
I'm trying to notify my customers that their subscription is about to expire. This is how I look for those users to notify them. They will be billed on the date they subscribed + 1.year:
User.where(subscribed_at: 53.weeks.ago.beginning_of_day..53.weeks.ago.beginning_of_day)
My question is will this create issue with leap years? or is there a better way to do this?
Upvotes: 2
Views: 151
Reputation: 54882
I think you should use 1.year.ago
since 52.weeks.ago
is not equal to a full year (52*7 = 364 days).
The usage of 1.year.ago
would be better because it actually changes the year
field of the DateTime, nothing else:
1.9.3p489 :005 > 2.year.ago
# => Mon, 15 Oct 2012 11:51:44 EDT -04:00
1.9.3p489 :006 > 5.year.ago
# => Thu, 15 Oct 2009 11:51:47 EDT -04:00
1.9.3p489 :007 > 999.year.ago
# => Sun, 15 Oct 1015 11:51:50 LMT -04:56 # For some reason the TimeZone changed!
In your case, I would use the following logic: NOPE NOPE, I would use @Stefan's answer!
range = (1.year.ago-1.week).beginning_of_day..(1.year.ago-1.week).end_of_day
User.where(subscribed_at: range)
Upvotes: 1
Reputation: 114138
Rails provides Time#advance
for "precise Time calculations":
Time.now.advance(years: -1, weeks: -1)
#=> 2013-10-08 17:54:36 +0200
Time#all_day
returns a whole day's range:
Time.now.advance(years: -1, weeks: -1).all_day
#=> 2013-10-08 00:00:00 +0200..2013-10-08 23:59:59 +0200
Upvotes: 2