如何获得下周的一周?

时间:2017-04-12 13:34:01

标签: ruby-on-rails ruby

我尝试了类似......

<%= Date.current.next_week.monday %>
<%= Date.current.next_week.tuesday %>
<%= Date.current.next_week.wednesday %>
<%= Date.current.next_week.thursday %>
<%= Date.current.next_week.friday %>

获取错误:ActionView::Template::Error (undefined method 'tuesday' for Mon, 17 Apr 2017:Date):

截至今天的日期,日期将是......

Apr 17
Apr 18
Apr 19
Apr 20
Apr 21

-

不重复(我不认为)。我尝试了那些答案。我无法在视图中呈现适当的日子。

2 个答案:

答案 0 :(得分:3)

next_week的语法需要调整:

# Works
<%= Date.current.next_week(:tuesday) %>

要了解原始方法无效的原因:mondaysunday恰好恰好在DateAndTime::Calculations上定义,但一周中的其他日子不是。{ / p>

答案 1 :(得分:1)

如果您需要使用纯Ruby,这是获得它的简单方法:

  • date减去cwday(日历周日)为您提供&#34;上周日&#34;
  • &#34;上周日+ 8&#34;给你&#34;下周一&#34;。
require 'date'

def next_week(date, day = :monday)
  days = %w(monday tuesday wednesday thursday friday saturday sunday)
  date - date.cwday + 8 + days.index(day.to_s.downcase).to_i
end

puts next_week(Date.today)
# 2017-04-17
puts next_week(Date.today, :friday)
# 2017-04-21
puts next_week(Date.new(2017,4,16))
# 2017-04-17
puts next_week(Date.new(2017,4,17))
# 2017-04-24

对于您的问题,您可以使用:

next_monday = next_week(Date.today)
puts working_days_next_week = Array.new(5){ |i| next_monday + i }
# 2017-04-17
# 2017-04-18
# 2017-04-19
# 2017-04-20
# 2017-04-21