Ruby on Rails - YouTube API - How to format duration ISO 8601 (PT45S)
Asked Answered
B

3

6

I've searched high and low and can't seem to find a straight answer on this. Basically, I'm calling the YouTube API and getting a JSON document back, then parsing it. Everything else is good, but I don't understand how to parse the 'duration' property to display it as human readable.

The 'duration' field comes over as 'PT1H5M34S' - 1 hour 5 minutes 34 seconds

Or it could be 'PT24S' - 24 seconds

Or 'PT4M3S' - 4 minutes 3 seconds

There has to be a way in Ruby to parse this string and make it human readable so that I can just pass in the duration on the fly in my loop and convert it. Any help or guidance is greatly appreciated. I've tried using Date.parse, Time.parse, Date.strptime, along with many other things... Like just gsub-ing the PT out of the string and displaying it, but that doesn't seem right.

Browder answered 8/10, 2014 at 16:40 Comment(0)
A
7

Try arnau's ISO8601 parser (https://github.com/arnau/ISO8601)

Usage:

 d = ISO8601::Duration.new('PT1H5M34S')
 d.to_seconds # => 3934.0
Ace answered 10/10, 2014 at 4:18 Comment(0)
K
0

A simple approach to get the number of seconds for videos less than 24 hours:

dur = "PT34M5S"
pattern = "PT"
pattern += "%HH" if dur.include? "H"
pattern += "%MM" if dur.include? "M"
pattern += "%SS"
DateTime.strptime(dur, pattern).seconds_since_midnight.to_i
Kutch answered 6/6, 2016 at 1:24 Comment(0)
B
0

You can use Rails ActiveSupport::Duration

parsed_duration = ActiveSupport::Duration.parse(youtube_duration)

Time.at(parsed_duration).utc.strftime('%H:%M:%S')
Bruis answered 9/2, 2021 at 9:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.