1

这是我关于 Stack 的第一个问题。

我正在一个预订网站上工作,该网站严重依赖搜索和寻找整周的住宿。大多数用户搜索将在一年中的第几周进行,例如。7 月的第一周第 27 周。

重要的是用户在搜索住宿时不需要填写年份,所以我们从用户那里得到的唯一信息就是周数。

考虑到它总是必须是该周数的下一个即将发生的事件,我如何从用户给出的周中获取年份?

(这有一个陷阱。我可以通过执行以下操作来获得即将到来的第 27 周:

def week
  week = 27
  Date.commercial(Date.current.year + 1, week, 1) # gives the first day of the week
end

但这只会在 1 月 1 日之前是正确的,之后它将寻找 2015 年的第 27 周。)

4

1 回答 1

1

您可以将当前日历周与Date.current.cweek (参考)与您的号码进行比较。

require 'active_support/core_ext' # Already included in Rails

def calendar_week(week)
  now = Date.current
  year = now.cweek < week ? now.year : now.year + 1
  Date.commercial(year, week, 1)
end

p calendar_week(49)
# => Mon, 02 Dec 2013

p calendar_week(1)
# => Mon, 30 Dec 2013 # don't know if that's the way calendar weeks are counted

p calendar_week(27)
# => Mon, 30 Jun 2014
于 2013-10-29T21:56:06.013 回答