Mani David
Mani David

Reputation: 1412

how get the last week start date and end date based on date in current week ruby

how to get the last week start date and end date based on date in current week ruby (Monday - Sunday)

Example: if date is 04-feb-15, then result should be start_date = Monday(26-jan-1015) end_date = Sunday(1-feb-15)

if date is 27-feb-15, , then result should be start_date = Monday(16-feb-1015) end_date = (22-feb-15)

Upvotes: 2

Views: 5852

Answers (5)

Shivkant Dohaliya
Shivkant Dohaliya

Reputation: 29

You can try this way

require 'active_support/core_ext/date/calculations'

monday = (Date.today.beginning_of_week.last_week)

sunday = (Date.today.beginning_of_week.last_week + 6)

More details on the ActiveSupport Date extensions: https://edgeguides.rubyonrails.org/active_support_core_extensions.html#extensions-to-date

Upvotes: 2

Bhaveshkumar
Bhaveshkumar

Reputation: 509

  • First date of last week

     Date.today.last_week.beginning_of_week
    
  • Last date of last week

     Date.today.last_week.at_end_of_week
    

Upvotes: 4

Mani David
Mani David

Reputation: 1412

i have tried the below code, working fine.

monday = (Date.today.beginning_of_week - 7) # 2015-01-26
sunday = (Date.today.end_of_week - 7) # 2015-02-01

Upvotes: 0

Sachin Gevariya
Sachin Gevariya

Reputation: 1167

You can try this way:

require 'date'
=> true

date = Date.today
=> #<Date: 2015-02-04 ((2457058j,0s,0n),+0s,2299161j)>

# date.wday return week day
end_date = date-date.wday
=> #<Date: 2015-02-01 ((2457055j,0s,0n),+0s,2299161j)>

start_date = date-date.wday-6
=> #<Date: 2015-01-26 ((2457049j,0s,0n),+0s,2299161j)>

For more operations you can refer this link Ruby Doc.

Upvotes: 4

Andrius Buivydas
Andrius Buivydas

Reputation: 271

Use Date#wday that tells with day of the week is for a given Date and then subtract accordinglly:

require 'date'

date = Date.parse("15-02-04")
monday = date - (date.wday + 6) # 2015-01-26
sunday = date - date.wday # 2015-02-01

date = Date.parse("15-02-27")
monday = date - (date.wday + 6) # 2015-02-16
sunday = date - date.wday # 2015-02-22

Upvotes: 0

Related Questions