4

I need to calculate in the format of 2014-01-20 the last two Sundays.

So, last_sunday = 2014-01-20 and most_recent_sunday = 2014-01-26.

I am using Rails 4.0 and Ruby 2.0. How can I get these dates?

Luigi
  • 5,443
  • 15
  • 54
  • 108

4 Answers4

6

In rails 4:

most_recent_sunday = Time.now.sunday.to_s

last_sunday =        Time.now.last_week.sunday.to_s

To get it to the format you are after:

DateTime.parse(most_recent_sunday).strftime("%Y-%m-%d")

http://apidock.com/rails/v4.0.2/DateAndTime/Calculations/sunday http://apidock.com/rails/v4.0.2/DateAndTime/Calculations/last_week

Kieran Andrews
  • 5,845
  • 2
  • 33
  • 57
  • Thanks for the tips - There's some helpful information on this here in TinMan's answer: http://stackoverflow.com/questions/279769/convert-to-from-datetime-and-time-in-ruby I actually had to attach a `.to_s` method on `most_recent_sunday` to get it to parse correctly, and include the dashes in the `.strftime` method. Also, `Time.now.sunday` actually returns this upcoming sunday, not the last sunday. Thanks for the help though, got me close enough to figure it out. – Luigi Jan 28 '14 at 13:39
  • Unless I'm missing something, this won't generalize to e.g. "Time.now.tuesday" – johncip Jan 29 '23 at 22:40
1

I suggest you take a look at the chronic gem

require 'chronic'
Chronic.parse("last sunday")
=> 2014-01-26 12:00:00 +0200

You can also use rail's active_support to subtract 7.days from the date computed above =)

Abdo
  • 13,549
  • 10
  • 79
  • 98
0
[11] pry(main)> last_sunday = Time.now - (Time.now.wday + 7) * 86400
=> 2014-01-19 17:17:19 -0600
[12] pry(main)> most_recent_sunday = Time.now - (Time.now.wday) * 86400
=> 2014-01-26 17:18:03 -0600
bjhaid
  • 9,592
  • 2
  • 37
  • 47
  • FYI if you start with Date.today or Time.zone.today then you don't need the `* 86400` because you'll already be dealing with days. So it suffices to do something like `t = Date.today; t - t.wday % 7`. – johncip Jan 29 '23 at 22:43
0

A pure Ruby solution:

require 'date'

last_two_weeks   = (Date.today-13)..Date.today
last_two_sundays = last_two_weeks.select &:sunday?

puts last_two_sundays #=> 2014-01-19, 2014-01-26
hirolau
  • 13,451
  • 8
  • 35
  • 47