Skip to content

Instantly share code, notes, and snippets.

@chriswessells
Created March 8, 2017 02:41
Show Gist options
  • Save chriswessells/aa6339d0723a9c1acb9ba91bf5f42140 to your computer and use it in GitHub Desktop.
Save chriswessells/aa6339d0723a9c1acb9ba91bf5f42140 to your computer and use it in GitHub Desktop.
Extend the ruby Date class to calculate the week function as MongoDB aggregations calculate the weeks
# Purpose: to extend the date class to match the week aggregation for MongoDB 3.2
#
require 'date'
class Date
def mongo_week_number
week_offset = 0
unless Date.new(self.year,1,1).wday == 0
week_offset = 7 - (Date.new(self.year,1,1).wday)
end
week_number = (self.yday.to_f - week_offset.to_f)/7
week_number.ceil
end
def mongo_week_ending
self + (6 - self.wday.to_i)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment