Panczo
Panczo

Reputation: 444

How to sum integers and convert this to time

I have a playlist with has_many tracks. Each track have time duration as integer in milliseconds. I want count total time duration for playlist. Actually i make something like this from my playlist model:

  def total_tracks_duration
    seconds = tracks.sum(:duration) / 1000
    Time.at(seconds).strftime("%H:%M:%S")
  end

Playlist spec:

it '#total_tracks_duration' do
    play = build(:playlist)
    3.times do
        create(:track, playlist: play, duration: 60000)
    end

    expect(play.total_tracks_duration).to eq("00:03:00")
end

And finally i have got this failure:

    Failures:

  1) Playlist #total_tracks_duration
     Failure/Error: expect(play.total_tracks_duration).to eq("00:03:00")

       expected: "00:03:00"
            got: "01:00:00"

       (compared using ==)
     # ./spec/models/playlist_spec.rb:51:in `block (2 levels) in <top (required)>'

Finished in 0.69605 seconds (files took 9.83 seconds to load)
1 example, 1 failure

Where i make mistake?

Upvotes: 1

Views: 250

Answers (1)

mswiszcz
mswiszcz

Reputation: 1006

It's adding an offset for your timezone (UTC+1), so simply do

Time.at(seconds).utc.strftime("%H:%M:%S")

and it should work :)

Upvotes: 2

Related Questions