Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/Rails get start, end date of a given week number of year

Base on the doc, I was able to get the current week number of current year :

Time.current.strftime('%V') => "23"

But I need methods that I can retrieve start date, end date of a given week number. In this example : 2016/06/06 -> 2016/06/12

any idea ?

like image 505
Duong Bach Avatar asked Mar 13 '23 02:03

Duong Bach


1 Answers

I think that you need to use ::commercial method from Date class like this.

require 'date'

week = 23
start_week = Date.commercial(2016, week, 1)
# => #<Date: 2016-06-06 ((2457546j,0s,0n),+0s,2299161j)>

end_week = Date.commercial(2016, week, 7)
# => #<Date: 2016-06-12 ((2457552j,0s,0n),+0s,2299161j)>

And if you want to print as you show in your example, do:

puts "#{start_week} -> #{end_week}"
# => 2016-06-06 -> 2016-06-12

Reference: http://ruby-doc.org/stdlib-2.3.1/libdoc/date/rdoc/Date.html#method-c-commercial

like image 86
WeezHard Avatar answered Mar 24 '23 01:03

WeezHard