[ACCEPTED]-Changing the first day of week in rails-datetime

Accepted answer
Score: 30

Nowadays the method accepts the start day 2 param:

beginning_of_week(start_day = :monday)

Note: param is supported from Rails 1 4.2.7 only

Score: 23

I've managed to make a pull request into 6 rails and now you can pass symbol argument 5 to beginning_of_week method. For example beginning_of_week(:sunday) will give you a 4 Sunday assuming that weeks starts on Sunday. The 3 same for end_of_week method. But you have to wait until 2 rails 3.2 release in case you are not on 1 the bleeding edge.

See this for more info: https://github.com/rails/rails/pull/3547

Score: 6

Add this config to config/application.rb

config.beginning_of_week = :sunday

0

Score: 4

You can work within the api by doing the 9 following:

ree-1.8.7-2011.02 :004 > DateTime.now.beginning_of_week
 => Mon, 30 May 2011 00:00:00 -0400 
ree-1.8.7-2011.02 :005 > DateTime.now.beginning_of_week.advance(:days => -1)
 => Sun, 29 May 2011 00:00:00 -0400 

EDIT:

Thinking about this the last 8 couple of minutes, there is good reason 7 for Rails approaching it this way. You have 6 to have a default start of the week, and 5 passing this optional parameter in, you 4 can now store the start of the week on say, the 3 User table in your database and allow the 2 user to pick which day of the week to start 1 their week, eg:

first_day_of_calendar_week = {:default => 0, :monday => 0, :sunday => -1 ..}
....
@user = User.find_by_some_attribute(...)
DateTime.now.beginning_of_week.advance(
  :days => first_day_of_calendar_week[@user.choice] || first_day_of_calendar_week[:default])
Score: 3

I don't know if it is something new, but 5 nowadays (Rais 4.2.5 - Ruby 2.2.3) you can 4 set Date.beginning_of_week = :sunday. I've tried to set this on config/application.rb but somehow 3 it doesn't work properly, probably it is 2 reset on every new request. Then I put this 1 on a before_action in my ApplicationController and works perfectly.

Score: 0

If you have a look at https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/date/calculations.rb#L178 you'll see that monday 2 is hardcoded as the first day. Sam's answer 1 is pretty good.

More Related questions