Hemanth's Scribes

ruby

Date Shifting in Ruby

Author Photo

Hemanth HM

Ruby has a hidden gem: the << shift operator on Date objects!

require 'date'
today = Date.today  # 2014-09-14

# Shift to previous month
last_month = today << 1
last_month.strftime('%B')  # "August"

# Shift to next months
next_month = today >> 2
next_month.strftime('%A-%B-%Y')  # "Friday-November-2014"

# Works on new dates too
Date.new(1988, 02, 01) >> 1  # 1988-03-01

Happy hacking! 🗓️

#ruby