Passing a day of the week into Ruby's Date.parse

How you can go about passing a day into Ruby's Date.parse

I’m sure you could guess that Ruby’s Date.parse can parse a date, as in, you give it a string reprenting a date and it turns it into a Date object.

You might even have guessted that if instead we used DateTime.parse we could also parse a time into our object.

But did you know you can pass a day of the week into Ruby’s Date.parse function? For example you could do something like this;

require 'date'

friday = Date.parse('Friday')

p friday => #<Date: 2013-07-12 ((2456486j,0s,0n),+0s,2299161j)>

This is pretty useful, it seems to return the date closest to the day you enter, and of course this will be based on your server’s date and time settings.

If you wanted to work out the date at the start of the current week and your week starts on Sunday, you could do something like;

require 'date'

sunday = Date.parse('Sunday')

if sunday > Date.today
    sunday -= 7
end

This is a super quick way of playing with dates without needing to rely on any gems.

    Recent posts View all

    Rails

    Dealing with multiple languages with inflections

    How to have your site deal with multiple languages in inflections

    Threat Intelligence JavaScript

    Threat Intelligence Issue 5

    Issue 5 of our Threat Intelligence information