如何在 Ruby 中获得两个日期之间的所有星期日? [英] How do I get all Sundays between two dates in Ruby?

查看:38
本文介绍了如何在 Ruby 中获得两个日期之间的所有星期日?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个表单,用户可以在其中输入日期范围并从复选框列表中选择一周中的一天/几天,即星期日、星期一、星期二、星期三、星期四、星期五和星期六.

I'm working on a form where the user enters a date range and selects from a list of checkboxes a day/days of the week i.e Sunday, Monday, Tuesday, Wednesday, Thursday, Friday and saturday.

提交表单后,我需要一种方法来获取基于所选日期输入的两个日期之间的日期列表,即给定的两个日期之间的所有星期一和星期四.我已经浏览了文档,但无法确定如何有效地执行此操作,即 ruby​​ 方式.

Once the form is submitted I need a way to grab a list of dates between the two dates entered based upon the days that were chosen i.e All Mondays and Thursdays between the two dates given. I've looked through the docs but can't pin point how to do this efficiently i.e the ruby way.

推荐答案

有趣的一个!:D

 start_date = Date.today # your start
 end_date = Date.today + 1.year # your end
 my_days = [1,2,3] # day of the week in 0-6. Sunday is day-of-week 0; Saturday is day-of-week 6.
 result = (start_date..end_date).to_a.select {|k| my_days.include?(k.wday)}

使用上面的数据,您将获得从现在到明年之间所有周一/周二/周三的数组.

using the data above you'll get an array of all Mon/Tue/Weds between now and next year.

这篇关于如何在 Ruby 中获得两个日期之间的所有星期日?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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