Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the date of "this Wednesday", "this Thursday" etc. in Rails

I know that Rails has an elegant way of getting dates for a certain day of the week for next week, or for last week (docs).

today = Time.zone.today
=> Fri, 24 Jan 2020

today.next_week
=> Mon, 27 Jan 2020 # Gets Monday by default

today.next_week(:thursday)
=> Thu, 30 Jan 2020 # You can get a certain day of the week by passing it in as an argument

Is there a way to do the same for this week? For example, getting the date of this Thursday, Friday, etc.? Right now, my workaround is to get the date of beginning_of_week (Monday) and calculate from there. Ideally, I wanted to do something similar to above, like Time.zone.today.this_week(:thursday).

this_monday = Time.zone.today.beginning_of_week
=> Mon, 20 Jan 2020

this_friday = this_monday.since(4.days).to_date
=> Fri, 24 Jan 2020
like image 366
reesaspieces Avatar asked Oct 27 '25 09:10

reesaspieces


1 Answers

You could use #next_occurring

pry(main)> Time.zone.today.beginning_of_week
Mon, 20 Jan 2020
pry(main)> Time.zone.today.beginning_of_week.next_occurring(:thursday)
Thu, 23 Jan 2020
like image 134
Jochen Lutz Avatar answered Oct 29 '25 22:10

Jochen Lutz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!