Chim Kan Chim Kan - 4 years ago 170
Ruby Question

Rails 3.2.8 - How do I get the week number from Rails?

I would like to know how to get the current week number from Rails and how do I manipulate it:


  1. Translate the week number into date.

  2. Make an interval based on week number.



Thanks.

Answer Source

Use strftime:

%U - Week number of the year. The week starts with Sunday. (00..53)
%W - Week number of the year. The week starts with Monday. (00..53)

Time.now.strftime("%U").to_i # 43

# Or...

Date.today.strftime("%U").to_i # 43

If you want to add 43 weeks (or days,years,minutes, etc...) to a date, you can use 43.weeks, provided by ActiveSupport:

irb(main):001:0> 43.weeks
=> 301 days

irb(main):002:0> Date.today + 43.weeks
=> Thu, 22 Aug 2013

irb(main):003:0> Date.today + 10.days
=> Sun, 04 Nov 2012

irb(main):004:0> Date.today + 1.years # or 1.year
=> Fri, 25 Oct 2013

irb(main):005:0> Date.today + 5.months
=> Mon, 25 Mar 2013
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download