Ruby(带Rails)将时间字符串转换为秒吗? [英] Ruby (with Rails) convert a string of time into seconds?

查看:73
本文介绍了Ruby(带Rails)将时间字符串转换为秒吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有很多时间...类似

So, I've got a string of time... something along the lines of

'4 hours'
'48 hours'
'3 days'
'15 minutes'

我想将所有这些转换成秒。对于'4小时',这可以正常工作

I would like to convert those all into seconds. For '4 hours', this works fine

Time.parse('4 hours').to_i - Time.parse('0 hours').to_i
=> 14400 # 4 hours in seconds, yay

但是,这在48小时内均无效(范围错误)。

However, this doesn't work for 48 hours (outside of range error). It also does not work for 3 days (no information error), etc.

是否有一种简单的方法可以将这些字符串转换为秒?

Is there a simple way to convert these strings into seconds?

推荐答案

您要Ruby对Time.parse进行的操作是确定一天中的时间。那不是你想要的。我能想到的所有库在这方面都是相似的:它们对绝对时间感兴趣,而不是时间长度。

What you're asking Ruby to do with Time.parse is determine a time of day. That's not what you are wanting. All of the libraries I can think of are similar in this aspect: they are interested in absolute times, not lengths of time.

要将字符串转换为我们可以使用的时间格式,我建议使用慢性( gem installchronic ) 。要转换为秒,我们可以相对于当前时间进行所有操作,然后减去该时间以获得所需的绝对秒数。

To convert your strings into time formats that we can work with, I recommend using Chronic (gem install chronic). To convert to seconds, we can do everything relative to the current time, then subtract that time to get the absolute number of seconds, as desired.

def seconds_in(time)
    now = Time.now
    Chronic.parse("#{time} from now", :now => now) - now
end

seconds_in '48 hours'   # => 172,800.0
seconds_in '15 minutes' # => 900.0
seconds_in 'a lifetime' # NoMethodError, not 42 ;)

几个快速笔记:


  • 从现在开始的 是需要慢性病的原因-它可以处理自然语言输入。

  • 我们指定 now 是安全的,以防万一Time.now从慢性做魔术的时间开始发生变化以及我们从结果中减去它的时间。它可能永远都不会发生,但是我认为这比后悔更好。

  • The from now is is why Chronic is needed — it handles natural language input.
  • We're specifying now to be safe from a case where Time.now changes from the time that Chronic does it's magic and the time we subtract it from the result. It might not occur ever, but better safe than sorry here I think.

这篇关于Ruby(带Rails)将时间字符串转换为秒吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆