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

后端 未结 4 912
难免孤独
难免孤独 2021-01-01 11:21

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
4条回答
  •  旧巷少年郎
    2021-01-01 11:37

    You are going to want to stay away from strftime("%U") and "%W".

    Instead, use Date.cweek.

    The problem is, if you ever want to take a week number and convert it to a date, strftime won't give you a value that you can pass back to Date.commercial.

    Date.commercial expects a range of values that are 1 based. Date.strftime("%U|%W") returns a value that is 0 based. You would think you could just +1 it and it would be fine. The problem will hit you at the end of a year when there are 53 weeks. (Like what just happened...)

    For example, let's look at the end of Dec 2015 and the results from your two options for getting a week number:

    Date.parse("2015-12-31").strftime("%W") = 52
    Date.parse("2015-12-31").cweek = 53
    

    Now, let's look at converting that week number to a date...

    Date.commercial(2015, 52, 1) = Mon, 21 Dec 2015
    Date.commercial(2015, 53, 1) = Mon, 28 Dec 2015
    

    If you blindly just +1 the value you pass to Date.commercial, you'll end up with an invalid date in other situations:

    For example, December 2014:

    Date.commercial(2014, 53, 1) = ArgumentError: invalid date
    

    If you ever have to convert that week number back to a date, the only surefire way is to use Date.cweek.

提交回复
热议问题