Reputation: 5795
I am trying to do reporting for a specific period, those periods supported being:
start = DateTime.now.beginning_of_day; end = start.end_of_day
start = DateTime.now.beginning_of_week; end = start.end_of_week
DateTime.now
)
cweek
is not used; the start of the first bi-week should be the first of the month, and the end of the second bi-week should be the last of the month. The dividing date between the two should be the total number of days in the month divided by 2, rounded up (i.e. if there are 31 days, the second bi-week would start on the 15th, and not the 14th of the month).start = DateTime.now.beginning_of_month; end = start.end_of_month
start = (DateTime.now - 1.month).beginning_of_month; end = start.end_of_month
start = DateTime.now.beginning_of_year --> end = start.end_of_year
I'm having trouble calculating the bold date ranges based on the current date (assume DateTime.now
).
How can I calculate the bi-weekly and quarterly period relative to the current date, DateTime.now
?
For the date May 7th, 2018 (5/7/2018):
5/1/2018
to 5/15/2018
4/1/2018
to 6/30/2018
For the date February 29th, 2020 (2/29/2020), a leap year:
2/15/2018
to 2/29/2018
1/1/2018
to 3/31/2018
Upvotes: 0
Views: 1496
Reputation: 10796
What about this:
This bi-week:
def bi_week_limits_for(date)
days_in_month = Time.days_in_month(date.month, date.year)
# this will round down. 30/31-day months will output 15. 28 / 29-day will output 14. Adjust as per your requirements
middle_day = days_in_month / 2
if date.day <= middle_day
[date.beginning_of_month, date.change(day: middle_day)]
else
[date.change(day: middle_day + 1), date.end_of_month]
end
end
In my console:
pry(main)> bi_week_limits_for Date.parse('29/2/2020')
=> [Sat, 15 Feb 2020, Sat, 29 Feb 2020]
pry(main)> bi_week_limits_for Date.parse('7/5/2018')
=> [Tue, 01 May 2018, Tue, 15 May 2018]
This quarter:
def bi_week_limits_for(date)
[date.beginning_of_quarter, date.end_of_quarter]
end
In my console
pry(main)> date = Date.parse('7/5/2018')
=> Mon, 07 May 2018
pry(main)> quarter_limits_for date
=> [Sun, 01 Apr 2018, Sat, 30 Jun 2018]
pry(main)> date = Date.parse '29/2/2020'
=> Sat, 29 Feb 2020
pry(main)> quarter_limits_for date
=> [Wed, 01 Jan 2020, Tue, 31 Mar 2020]
Reference: https://apidock.com/rails/DateAndTime/Calculations/beginning_of_quarter
Upvotes: 5