Ruby - 如何查找给定小时的NEXT事件?

问题描述 投票:1回答:5

我想返回一个Ruby qazxsw poi对象(毫秒),表示给定DateTime的下一个X小时。

下一个凌晨5点的例子

  • 如果目前是3/28的晚上9点,那么下午5点将是3/29凌晨5点
  • 如果它目前是3月29日早上6点,那么下午5点将是3/30凌晨5点30分

代码明智:

Time

我想要一些灵活的东西,如果# for the below attribute @object.created_at => "2017-03-28 21:00:00" # given the definition of the next X hour in question next_hour_to_find = 5 # for 5am # what's the equation to produce 3/29 5am? 然后该功能将能够找到下一个下午2点。不用担心时区,这都属于next_hour_to_find = 14时区的范围。

我目前的想法如下,但我觉得有一种更清洁的方式......

@object.created_at
ruby-on-rails ruby date datetime time
5个回答
1
投票

没有理由用字符串格式的时间粉碎。 DateTime对象包含您需要的所有内容:

if @object.created_at.hour > next_hour_to_find
  # the next X hour is always going to occur on the next date
  date = (@object.created_at + 1.days).strftime(...) # get the date out
else
  # the next X hour is always going to occur on the same date
  date = (@object.created_at).strftime(...) # get the date out
end

# now that we have a date in a string, we have to append that string with the next_hour_to_find
# not sure if below works for both single and double digit hours
string = date + next_hour_to_find + ":00:00"

# finish by returning Time object, but this seems suuuuper inefficient since we converted to string and then back again
return Time.parse(string)

2
投票

您可能想查看now = DateTime.now if (now.hour >= 5) now = now.advance(days: 1) end now.change(hour: 5) ,这是一个很棒的库,在Ruby中使用日期时允许使用自然语言。

Chronic

由于Chronic返回常规five_today = Chronic.parse('5am') five_today < Time.now ? Chronic.parse('tomorrow 5am') : five_today Date对象,这也可以在没有它的情况下工作。但是,你的语法不太令人愉快。


0
投票

以下怎么样?

Time

基本上它的作用是:

  • 它查看了def next_hour_from(time, next_hour_to_find) hour_on_day_of_time = next_hour_to_find.hours.since( time.beginning_of_day ) hour_on_day_of_time < time ? 1.day.since(hour_on_day_of_time) : hour_on_day_of_time end # e.g. next_hour_from(@object.created_at, 5) # @object.created_at #=> 2017-03-28 21:00:00 # => 2017-03-29 05:00:00 当天开始的时间,并在几小时内添加了time。将该值分配给next_hour_to_find
  • 然后检查hour_on_day_of_time是否在给定的hour_on_day_of_time之前或之后。如果它在之后,则该方法可以返回time。如果是之前,它会向hour_on_day_of_time增加1天并返回。

0
投票

这是一个纯粹的Ruby答案。我假设24小时制。如果需要12小时制,则可以将12小时时间(例如hour_on_day_of_time)转换为(3pm)作为预备步骤。

15

假设

require 'time'

dt = DateTime.now
  #=> #<DateTime: 2017-03-31T00:18:08-07:00\
  #     ((2457844j,26288s,566004000n),-25200s,2299161j)> 

然后

next_hr = 15

-1
投票

为我的用例提供了更复杂的解决方案

Time.new(dt.year, dt.month, dt.day, dt.hour) +
  3600 * ((dt.hour < next_hr) ? next_hr - dt.hour : 24 + next_hr - dt_hour)
  #> 2017-03-31 15:00:00 -0700

它接受输入为字符串,有或没有时区。就我而言,这是必要的。

© www.soinside.com 2019 - 2024. All rights reserved.