How to format duration ISO 8601 (PT45S)

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.


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

Usage:

 d = ISO8601::Duration.new('PT1H5M34S')
 d.to_seconds # => 3934.0

一个简单的方法来获得少于24小时的视频秒数:

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
链接地址: http://www.djcxy.com/p/95420.html

上一篇: 在.rb文件中声明变量会导致不需要的输出

下一篇: 如何格式化持续时间ISO 8601(PT45S)