Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get the current weekday beginning in ruby?

For example today is 28/07/2011 How do i get the weeks first day the monday which is 25/07/2011 in ruby

like image 303
ahmet Avatar asked Jul 28 '11 12:07

ahmet


2 Answers

>> Date.today.beginning_of_week.strftime('%d/%m/%Y')
#=> 25/07/2011

See the Time and Date classes under Rails for more info, and strftime for information on the formatting options.

like image 177
Chowlett Avatar answered Nov 13 '22 05:11

Chowlett


Without Rails/ActiveSupport:

phrogz$ irb
> require 'date'
> now = Date.today
#=> #<Date: 2011-07-28 (4911541/2,0,2299161)>
> sunday = now - now.wday
#=> #<Date: 2011-07-24 (4911533/2,0,2299161)>
> monday = now - (now.wday - 1) % 7
#=> #<Date: 2011-07-25 (4911535/2,0,2299161)>
> monday.iso8601
#=> "2011-07-25"
> monday.strftime('%d/%m/%Y')
#=> "25/07/2011"

For more, see the Date class in the Standard Library.

Wrapped up as a method:

require 'date'
# For weekdays to start on Monday use 1 for the offset; for Tuesday use 2, etc.
def week_start( date, offset_from_sunday=0 )
  date - (date.wday - offset_from_sunday)%7
end

sun = Date.parse '2011-07-24'
week_start(sun,0).strftime('%a, %b-%d')  #=> "Sun, Jul-24"
week_start(sun,1).strftime('%a, %b-%d')  #=> "Mon, Jul-18"
like image 23
Phrogz Avatar answered Nov 13 '22 04:11

Phrogz