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

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;

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;

sunday = Date.parse('Sunday')
if sunday >
    sunday -= 7

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

Share this on
  • mog

    Date.current.beginning_of_week if you have ActiveSupport, which is pretty standard.

  • Toby Osbourn

    Cheers @mog:disqus – of course you are right, but with what I was doing I didn’t want to jump into anything else.

    I also noticed when testing that `beginning_of_week` for me was set to be a Monday, I am sure this is something I can change but I quite like telling Ruby exactly when I want my date to be.

  • max

    be careful with Date.parse – it is quite slow. for instance when you have a string with date in some(known) format – it’s lightyears faster to regexp the crap out of it than to use Date.parse

  • Toby Osbourn

    Cheers for the heads up @23c0c588fc16ff876a6c6e30529ed37d:disqus – I hadn’t benchmarked it at all.

  • Luke Griffiths

    Good to know Toby! Just wanted to add that in order to use this method from a straight irb session (not a rails console), you need to `require ‘date’` which loads the standard implementation. Kinda counter-intuitive. Thanks to