我想知道如何从 Rails 获取当前周数以及如何操作它:
- 将周数转换为日期。
- 根据周数进行间隔。
谢谢。
使用strftime
:
%U
- 一年中的周数。一周从星期日开始。(00..53)
%W
- 一年中的周数。一周从星期一开始。(00..53)
Time.now.strftime("%U").to_i # 43
# Or...
Date.today.strftime("%U").to_i # 43
如果您想将43 周(或天、年、分钟等)添加到日期,您可以使用43.weeks
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
你会想要远离strftime("%U")
and "%W"
。
相反,使用Date.cweek
.
问题是,如果您想要获取周数并将其转换为日期,strftime
则不会给您一个可以传回的值Date.commercial
。
Date.commercial
期望一个基于 1 的值范围。
Date.strftime("%U|%W")
返回一个基于 0 的值。你会认为你可以 +1 就可以了。问题将在一年结束时出现,那时有 53 周。(就像刚刚发生的那样……)
例如,让我们看一下 2015 年 12 月末以及您获得周数的两个选项的结果:
Date.parse("2015-12-31").strftime("%W") = 52
Date.parse("2015-12-31").cweek = 53
现在,让我们看一下将该周数转换为日期...
Date.commercial(2015, 52, 1) = Mon, 21 Dec 2015
Date.commercial(2015, 53, 1) = Mon, 28 Dec 2015
如果您盲目地 +1 传递给 的值Date.commercial
,则在其他情况下您最终会得到无效的日期:
例如,2014 年 12 月:
Date.commercial(2014, 53, 1) = ArgumentError: invalid date
如果您必须将该周数转换回日期,唯一可靠的方法是使用Date.cweek
.
date.commercial([cwyear=-4712[, cweek=1[, cwday=1[, start=Date::ITALY]]]]) → date
Creates a date object denoting the given week date.
The week and the day of week should be a negative
or a positive number (as a relative week/day from the end of year/week when negative).
They should not be zero.
对于区间
require 'date'
def week_dates( week_num )
year = Time.now.year
week_start = Date.commercial( year, week_num, 1 )
week_end = Date.commercial( year, week_num, 7 )
week_start.strftime( "%m/%d/%y" ) + ' - ' + week_end.strftime("%m/%d/%y" )
end
puts week_dates(22)
EG:输入(周数):22
输出:06/12/08 - 06/19/08
信用:Siep Korteling http://www.ruby-forum.com/topic/125140
Date#cweek
似乎%V
在 strftime 中获得了 ISO-8601 周数(基于星期一的一周)(@Robban 在评论中提到)。
例如,我正在写这个星期的星期一和星期日:
[ Date.new(2015, 7, 13), Date.new(2015, 7, 19) ].map { |date|
date.strftime("U: %U - W: %W - V: %V - cweek: #{date.cweek}")
}
# => ["U: 28 - W: 28 - V: 29 - cweek: 29", "U: 29 - W: 28 - V: 29 - cweek: 29"]