Duong Bach Duong Bach - 5 months ago 37
Ruby Question

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 ?

Answer

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

Comments