如何知道今天的日期是否在日期范围内?
我有一个带有 start_time
和 end_time
的事件,并且想要检查该事件是否“正在进行”。那将检查今天的日期是否在两个日期之间的范围内。
您将如何在函数中执行此操作?
I have an event with start_time
and end_time
and want to check if the event is "in progress". That would be to check if today's date is in the range between the two dates.
How would you do this in a function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
在 Ruby 1.9.2
===
中不起作用,我收到错误:改为使用
#cover?
:In Ruby 1.9.2
===
doesn't work, I get an error:Instead use
#cover?
:使用
===
实际上,有一个运算符可以做到这一点。创建一个
Range
并使用===
运算符将Time
对象与其进行比较。Update post-comment-flood: This version works well everywhere. (In Rails, in Ruby 1, and in Ruby 2.) The earlier
irb
example also worked fine but the interactive example wasn't always reproduced correctly in some experiments. This one is easier to cut-and-paste.现在一切都已经理顺了。
Use
===
Actually, there is an operator that will do this. Make a
Range
and compareTime
objects to it using the===
operator.Update post-comment-flood: This version works well everywhere. (In Rails, in Ruby 1, and in Ruby 2.) The earlier
irb
example also worked fine but the interactive example wasn't always reproduced correctly in some experiments. This one is easier to cut-and-paste.It's all straightened out now.
如果您使用 Rails,则可以使用
TimeWithZone# Between?
。然后你会得到这样的东西:If you're using Rails you can use
TimeWithZone#between?
. You'd then have something like this:由于日期类包含 Comparable 模块,因此每个日期对象都有一个
Between? 方法。
Because the date class includes the Comparable module, every date object has a
between?
method.概括
summary
如果您使用 Rails,您可以尝试以下操作:
注意:我只是使用
beginning_of_day
和end_of_day
来提供一个简单的范围。重要的部分是 Range 上的include_with_range?
方法。If you are using Rails, you could try this:
Note: I just used
beginning_of_day
andend_of_day
to provide an easy range. The important part is theinclude_with_range?
method on a Range.如果它们是时间戳:
If they're timestamps:
检查的是两个日期之间的当前日期。使用红宝石
Checked is current date in between two dates. Using Ruby
这可能会对某些人有所帮助。
ruby 只能理解计算之间的日期,如果日期格式如下:
不
如果你以错误的方式进行操作,它会给你一个误报。
现在效果很好
Thit may help some one out there.
ruby only can understand date between calculations if the date format like this :
not
If you do it the wrong way it will give you a false positive.
This works perfectly now