Ruby Ruby 中的 Time 有没有什么方法舍弃掉分钟和秒

ThanksSirAlec · April 16, 2019 · Last by sevk replied at April 17, 2019 · 3260 hits

目前的做法是

time = Time.now
new_time = Time.new(time.year, time.month, time.day, time.hour)

有没有更好的方法

Time.now.methods -> Time.now.methods.grep(/at/) -> Time.now.at_beginning_of_hour

Time.now.strftime('%Y-%m-%d %H:00:00') 这个符合你的要求吗

Reply to yfscret

这个不行,因为最后还要 .to_i 存进 db

多谢,忘了还有active_support了。。。

或者可以把不到 3600 秒的部分减掉:Time.now.to_i - Time.now.to_i % 3600

这是个做时间序列应用时经常会用到的 tips。

Time.at(Time.now.to_i / 3600 * 3600)

需要按多少秒分割,先除以它再乘以它就好了

irb(main):001:0> require 'date'
=> true
irb(main):002:0> Time.now.strftime("%Y%m%d%H").to_i
=> 2019041612

这样?

Time.now.to_i / 3600

ThanksSirAlec closed this topic. 18 Apr 10:24
You need to Sign in before reply, if you don't have an account, please Sign up first.