gpt4 book ai didi

ruby-on-rails - ruby 日期时间 : Get next 5:15pm (or similar)

转载 作者:数据小太阳 更新时间:2023-10-29 07:14:09 26 4
gpt4 key购买 nike

因此,给定一个 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

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

最佳答案

我将只构建一次新的日期时间,并在需要时添加 1 天:

# Given fixed_time and date_time
new_date_time = DateTime.new(
date_time.year,
date_time.month,
date_time.day,
fixed_time.hour,
fixed_time.min,
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

关于ruby-on-rails - ruby 日期时间 : Get next 5:15pm (or similar),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37229796/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com