Does Ruby (with Rails) convert a time string to seconds?

So I have a time sequence ... something like strings

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

I would like to convert it all in a matter of seconds. For '4 hours'it works great

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

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

Is there an easy way to convert these strings to seconds?


+3
source share
6 answers

What you ask Ruby to do with Time.parse determines the time of day. This is not what you want. All the libraries that I can think of are similar in this respect: they are interested in absolute times rather than length of time.

, , Chronic (gem install chronic). , , , , .

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 ;)

:

  • from now - , Chronic - .
  • now, , Time.now , Chronic , , . -, , , .
+6
4.hours => 14400 seconds
4.hours.to_i 14400
4.hours - 0.hours => 14400 seconds 

def string_to_seconds string
  string.split(' ')[0].to_i.send(string.split(' ')[1]).to_i
end

, [] ()/ ()/ ()

+3
'48 hours'.match(/^(\d+) (minutes|hours|days)$/) ? $1.to_i.send($2) : 'Unknown'
 => 172800 seconds
+3

I am sure you will get a good job from chronic gem.

Also, here are some good to know ruby ​​dates / times information

+1
source

Chronic will work, but Chronic Duration is better suited. It can parse a string and give you seconds.

ChronicDuration :: parse ('15 minutes ') or ChronicDuration :: parse (' 4 hours)

http://everydayrails.com/2010/08/11/ruby-date-time-parsing-chronic.html

0
source
>> strings = ['4 hours', '48 hours', '3 days', '15 minutes', '2 months', '5 years', '2 decades']
=> ["4 hours", "48 hours", "3 days", "15 minutes", "2 months", "5 years", "2 decades"]
>> ints = strings.collect{|s| eval "#{s.gsub(/\s+/,".")}.to_i" rescue "Error"}
=> [14400, 172800, 259200, 900, 5184000, 157788000, "Error"]
-1
source

Source: https://habr.com/ru/post/1784040/


All Articles