Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Date Shifting in Ruby

| Comments

Ruby is a langauge that had many hidden gems, one such is using the << shift operator on Date objects!

Consider the following scenarii:

  • We get the current date.

  • We need to day of previous or the next month for the same date.

1
2
3
4
5
6
7
8
9
10
11
12
13
require 'date'

today = Date.today
# => #<Date: 2014-09-14 ((2456915j,0s,0n),+0s,2299161j)> 

today.strftime('%A')
# => "Sunday"

today.strftime('%B')
# => "September" 

today.strftime('%Y')
# => 2014

Now let's do the shifting:

1
2
3
4
5
6
7
8
9
10
11
last_month = today << 1
# => #<Date: 2014-08-14 ((2456884j,0s,0n),+0s,2299161j)> 

last_month.strftime('%A')
# => "Thursday" 

last_month.strftime('%B')
# => "August" 

last_month.strftime('%Y')
# => "2014" 
1
2
3
4
5
next_month = today >> 2
# => #<Date: 2014-11-14 ((2456976j,0s,0n),+0s,2299161j)> 

next_month.strftime('%A-%B-%Y')
# => "Friday-November-2014" 

We could also shift on the new date:

1
2
Date.new(1988, 02, 01) >> 1
# => #<Date: 1988-03-01 ((2447222j,0s,0n),+0s,2299161j)> 

That's all for now, happy hacking! :)

Comments