I need to get time value of DD:hh:mm:ss into seconds. Value is an output from a postgresql db query and looks something like this:

db_value = '456:14:56:10'

and I need to get it into seconds, I have an method in my application which does vice versa like this:

def time_converter(seconds)
  days = seconds / 86400
  seconds -= days * 86400
  hours = seconds / 3600
  seconds -= hours * 3600         
  minutes = seconds / 60
  seconds -= minutes * 60
  return "#{days}:#{hours}:#{minutes}:#{seconds}"

Can I use this method somehow or is it possible to change format in postgresql into seconds? What is the most efficient way of doing it?

db value is part of a SUM((end_time - start_time)* multiplier) AS duration query.

有帮助吗?

解决方案

You didn't state which version of ruby you were using, so I'm assuming something modern. This should work on 1.9.3 or later. This also assumes that you always have all 4 fields present. It should give you some ideas anyway.

> db_value = '456:14:56:10'
=> "456:14:56:10"
> units = %w{days hours minutes seconds}
=> ["days", "hours", "minutes", "seconds"]
> db_value.split(":").map.with_index{|x,i| x.to_i.send(units[i])}.reduce(:+).to_i
=> 39452170
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top