Rails 5.2 Date#prev_occurring & Date#next_occurring

Sushant Mittal

By Sushant Mittal

on April 17, 2018

This blog is part of our  Rails 5.2 series.

Before Rails 5.2, this is how we would write to find next or previous occurring day of the week.

Assume that current date is Tue, 27 Feb 2018.

1# find previous thursday
2>> Date.yesterday.beginning_of_week(:thursday)
3=> Thu, 22 Feb 2018
4
5# find next thursday
6>> Date.tomorrow.end_of_week(:friday)
7=> Thu, 01 Mar 2018
8

Rails 5.2 has introduced methods Date#prev_occurring and Date#next_occurring to find next & previous occurring day of the week.

1# find previous thursday
2>> Date.prev_occurring(:thursday)
3=> Thu, 22 Feb 2018
4
5# find next thursday
6>> Date.next_occurring(:thursday)
7=> Thu, 01 Mar 2018

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.