Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last Sunday of the Month

Tags:

ruby

chronic

I'm using Chronic to get the last Sunday of the month of any given year. It will gladly give me the n‌th Sunday, but not the last.

This works, but is not what I need:

Chronic.parse('4th sunday in march', :now => Time.local(2015,1,1))

This is what I need, but doesn't work:

Chronic.parse('last sunday in march', :now => Time.local(2015,1,1))

Is there any way around this apparent limitation?

UPDATE: I'm upvoting the two answers below because they're both good, but I've already implemented this in "pure Ruby" (in 2 lines of code, besides the require 'date' line), but I'm trying to demonstrate to management that Ruby is the right language to use to replace a Java codebase that is going away (and which had dozens of lines of code to compute this), and I told one manager that I probably could do it in one line of Ruby, and it would be readable and easy to maintain.

like image 686
iconoclast Avatar asked Jul 31 '13 14:07

iconoclast


People also ask

How to get the last Sunday of the month?

You take a date and shift it forward to the last day of the month. Then you shift that last day of the month back to the first day of the week the last day of the month is in.

How to get last Sunday of month in JavaScript?

Get the weekday with getDate (note 0-6 in Javascript is from Sunday to Saturday) and if this day is a Sunday (=0) then assign 7. Build a new date from the first of next month, subtract the day difference, and set it as new date. By using this trick you get the last Sunday of a month.

How to get last Sunday date in JavaScript?

To get the date of the previous Sunday, use the setDate() method, setting the date to the result of subtracting the day of the week from the day of the month. The setDate method changes the day of the month of the specific Date instance.


1 Answers

I am not sure about Chronic (I haven't heared about it before), but we can implement this in pure ruby :)

##
# returns a Date object being the last sunday of the given month/year
# month: integer between 1 and 12
def last_sunday(month,year)
  # get the last day of the month
  date = Date.new year, month, -1
  #subtract number of days we are ahead of sunday
  date -= date.wday
end

The last_sunday method can be used like this:

last_sunday 07, 2013
#=> #<Date: 2013-07-28 ((2456502j,0s,0n),+0s,2299161j)>
like image 116
tessi Avatar answered Oct 08 '22 11:10

tessi