How to add hours and minutes that are stored as strings

  • A+
Category:Languages

I'm trying to add hours and minutes that are stored in the database like this:

+----+---------+-------+ | id | user_id | time  | +----+---------+-------+ |  1 |       4 | 03:15 | |  2 |       4 | 02:22 | +----+---------+-------+ 

The time field is a string. How can I add the hours and minutes expressed by the strings like 05:37?

I tried this

current_user.table.pluck(:time).sum(&:to_f) 

but the output is only 5.

 


If you read the times from your table into an array you obtain something like

arr = ["03:15", "02:22"] 

You could then write

arr.sum do |s|   h, m = s.split(':').map(&:to_i)   60*h + m end.divmod(60).join(':')   #=> "5:37" 

The three steps are as follows.

mins = arr.sum do |s|   h, m = s.split(':').map(&:to_i)   60*h + m end   #=> 337 hm = mins.divmod(60)   #=> [5, 37] hm.join(':')   #=> "5:37" 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: