计算不包括周末的天数 [英] Counting days excluding weekends

查看:56
本文介绍了计算不包括周末的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Ruby on Rails 中创建一个图书馆风格的系统,我正在尝试想出一种方法来计算逾期天数,同时排除借出物品归还的周末.现在我只是计算dayslate"作为截止日期和物品实际退回日期之间的差异,但我想排除周末,因为物品只能在工作日退回.

I'm creating a library-style system in Ruby on Rails, and I'm trying to come up with a way to calculate the overdue days while excluding weekends when a borrowed item is returned. Right now I'm just calculating "dayslate" as the difference between the due date and the date the item was actually returned, but I want to exclude weekends, since items can only be returned on weekdays.

这是我第一次真正体验 Ruby 和 Rails,所以如果我遗漏了一些明显的东西,我深表歉意.感谢大家提供的任何帮助.

This is my first real experience with Ruby and Rails, so my apologies if I'm missing something obvious. Thanks for any help you all can provide.

这是我的返回"函数代码:

Here's the code I have for the "return" function:

   def return
     @product = Product.find(params[:id])
     today = Date.today
     dayslate = today - @product.due_date
     if @product.due_date >= today
       @product.borrower = @product.check_out = @product.due_date = @product.extended_checkout = nil
       @product.save!
       flash[:notice] = "Okay, it's checked in!"
       redirect_to(products_url)
     else
       @product.borrower = @product.check_out = @product.due_date = @product.extended_checkout = nil
       @product.save!
       flash[:notice] = "Checked in, but it was #{dayslate} days late!"
       redirect_to(products_url)
     end
 end 

推荐答案

这里有一段代码,用于在 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

这篇关于计算不包括周末的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆