如何对整数求和并将其转换为时间
How to sum integers and convert this to time
我有一个包含 has_many 首曲目的播放列表。每个轨道的持续时间都是以毫秒为单位的整数。
我想计算播放列表的总持续时间。事实上,我从我的播放列表模型中制作了这样的东西:
def total_tracks_duration
seconds = tracks.sum(:duration) / 1000
Time.at(seconds).strftime("%H:%M:%S")
end
播放列表规范:
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
最后我遇到了这个失败:
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
我哪里弄错了?
它为您的时区 (UTC+1) 添加了一个偏移量,所以只需这样做
Time.at(seconds).utc.strftime("%H:%M:%S")
它应该可以工作:)
我有一个包含 has_many 首曲目的播放列表。每个轨道的持续时间都是以毫秒为单位的整数。 我想计算播放列表的总持续时间。事实上,我从我的播放列表模型中制作了这样的东西:
def total_tracks_duration
seconds = tracks.sum(:duration) / 1000
Time.at(seconds).strftime("%H:%M:%S")
end
播放列表规范:
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
最后我遇到了这个失败:
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
我哪里弄错了?
它为您的时区 (UTC+1) 添加了一个偏移量,所以只需这样做
Time.at(seconds).utc.strftime("%H:%M:%S")
它应该可以工作:)