且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算不包括周末的天数

更新时间:2023-01-31 14:19:17

这里有一段代码,用于在 Date 对象范围内查找工作日数

Here's a snippet of code to find the number of weekdays in a Range of Date objects

require 'date'
# Calculate the number of weekdays since 14 days ago
p ( (Date.today - 14)..(Date.today) ).select {|d| (1..5).include?(d.wday) }.size

这就是我在你的情况下使用它的方式.

This is how I would use it in your case.

class Product
  def days_late
    weekdays_in_date_range( self.due_date..(Date.today) )
  end

  protected
  def weekdays_in_date_range(range)
    # You could modify the select block to also check for holidays
    range.select { |d| (1..5).include?(d.wday) }.size
  end
end