Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the first day of week in rails

I and trying to build a calendar in ruby on rails.

In ruby-on-rails, monday is considered to be the first day of the week, but i have to set sunday as the first. I intend to change this to properly use the date's built-in methods RoR. Assuming today is sunday, oct 24th. Look the example:

Date.now.beginning_of_week

it prints: 2010-10-18 ;but if i could set sunday as the first of the week, it should print : 2010-10-24

like image 800
Thiago Diniz Avatar asked Oct 24 '10 20:10

Thiago Diniz


4 Answers

Nowadays the method accepts the start day param:

beginning_of_week(start_day = :monday)

Note: param is supported from Rails 4.2.7 only

like image 152
cortex Avatar answered Oct 11 '22 09:10

cortex


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

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

like image 28
gregolsen Avatar answered Oct 11 '22 09:10

gregolsen


Add this config to config/application.rb

config.beginning_of_week = :sunday
like image 39
Penguin Avatar answered Oct 11 '22 09:10

Penguin


You can work within the api by doing the 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 couple of minutes, there is good reason for Rails approaching it this way. You have to have a default start of the week, and passing this optional parameter in, you can now store the start of the week on say, the User table in your database and allow the user to pick which day of the week to start 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])
like image 32
Jed Schneider Avatar answered Oct 11 '22 08:10

Jed Schneider