Hemanth's Scribes

ruby

Date Shifting in Ruby

Author Photo

Hemanth HM

Thumbnail

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
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.