Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Year-Month-Date of last Sunday

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?

like image 602
Luigi Avatar asked Mar 21 '23 19:03

Luigi


2 Answers

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

like image 151
Kieran Andrews Avatar answered Apr 02 '23 05:04

Kieran Andrews


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 =)

like image 21
Abdo Avatar answered Apr 02 '23 05:04

Abdo