Chris Cirefice
Chris Cirefice

Reputation: 5795

Ruby(/Rails) dates - bi-weekly and quarterly DateTime ranges

I am trying to do reporting for a specific period, those periods supported being:

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?

Expected output

For the date May 7th, 2018 (5/7/2018):

For the date February 29th, 2020 (2/29/2020), a leap year:

Upvotes: 0

Views: 1496

Answers (1)

dgilperez
dgilperez

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

Related Questions