【发布时间】:2016-09-10 19:39:27
【问题描述】:
因此,给定一个 DateTime 对象和一个固定时间,我想在给定 DateTime 对象之后获取下一次出现的固定时间。
例如,给定 2016 年 3 月 14 日下午 4:00 的日期和下午 5:15 的时间,我想返回 2016 年 3 月 14 日 下午 5:15。
但是,鉴于日期为 2016 年 3 月 14 日下午 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.hour,
fixed_time.min,
fixed_time.sec
)
end
# Return new_time
有效,但有更好的方法吗?
【问题讨论】:
标签: ruby-on-rails ruby datetime ruby-on-rails-4 time