加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Ruby DateTime:下一个下午5:15(或类似)

发布时间:2020-12-17 03:33:00 所属栏目:百科 来源:网络整理
导读:因此,给定DateTime对象和固定时间,我想在给定的DateTime对象之后获得下一次固定时间的出现. 例如,考虑到2016年3月14日,下午4:00和下午5:15的时间,我想在2016年3月14日下午5:15返回. 但是,下午6:00和下午5:15的时间,我想要返回2016年3月15日下午5:15,因为那是
因此,给定DateTime对象和固定时间,我想在给定的DateTime对象之后获得下一次固定时间的出现.

>例如,考虑到2016年3月14日,下午4:00和下午5:15的时间,我想在2016年3月14日下午5:15返回.
>但是,下午6:00和下午5:15的时间,我想要返回2016年3月15日下午5:15,因为那是下一次发生的事情.

到目前为止,我已经编写了这段代码:

# Given fixed_time and date_time

new_time = date_time
if fixed_time.utc.strftime("%H%M%S%N") >= date_time.utc.strftime("%H%M%S%N")
  new_time = DateTime.new(
    date_time.year,date_time.month,date_time.day,fixed_time.hour,fixed_time.min,fixed_time.sec
  )
else
  next_day = date_time.beginning_of_day + 1.day
  new_time = DateTime.new(
    next_day.year,next_day.month,next_day.day,fixed_time.sec
  )
end

# Return new_time

它有效,但有更好的方法吗?

解决方法

我只需要构建一次新的日期时间,如果需要,可以添加1天:

# Given fixed_time and date_time
new_date_time = DateTime.new(
  date_time.year,fixed_time.sec
)

# add 1 day if new date prior to the given date
new_date_time += 1.day if new_date_time < date_time

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读