以下 Ruby 代码获取每个月的第一天:
require 'active_support/all'
# get the date at the beginning of this month
date = Date.today.beginning_of_month
# get the first day of the next 5 months
5.times do |num|
date = date.next_month
p date
end
给出:
=> Fri, 01 Aug 2014
=> Mon, 01 Sep 2014
=> Wed, 01 Oct 2014
=> Sat, 01 Nov 2014
=> Mon, 01 Dec 2014
但是我如何获得每个月的第一个星期四呢?即
=> Thu, 07 Aug 2014
=> Thu, 04 Sep 2014
=> Thu, 02 Oct 2014
=> Thu, 06 Nov 2014
=> Thu, 04 Dec 2014
最佳答案
不需要迭代或条件,只需得到所谓的直到下星期四的天数增量:
#4 is thursday because wday starts at 0 (sunday)
date = Date.today.beginning_of_month
date += (4 - date.wday) % 7
p date
=> Thu, 03 Jul 2014
关于ruby-on-rails - 我如何在 Ruby/Rails 中获得每月的第一个星期四?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24508787/