admin管理员组文章数量:1425717
I write a small feature to search videos in YouTube with YouTube API v3
The format of video duration like PT2M54S
I would like to convert it as 00:02:54
use moment.js
Have any solutions?
I write a small feature to search videos in YouTube with YouTube API v3
The format of video duration like PT2M54S
I would like to convert it as 00:02:54
use moment.js
Have any solutions?
Share Improve this question asked Feb 27, 2017 at 3:24 Thanh DaoThanh Dao 1,2602 gold badges18 silver badges44 bronze badges3 Answers
Reset to default 4You can create a moment.duration
object and then format it using moment-duration-format plug-in. The library adds format
method to durations and has the trim
option that lets you get the output in the format you asked.
A sample code is the following:
var dur = moment.duration('PT2M54S');
console.log( dur.format('HH:mm:ss', {trim: false}) ); // 00:02:54
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
I'm recreating the YouTube iOS app and use moment + moment-duration-format to create the running times in the bottom corner of a video (e.g. 4:05).
If you're interested in that, I offer this utility function:
import moment from 'moment';
import 'moment-duration-format';
export default (duration) => moment
.duration(duration)
.format('h:mm:ss')
.padStart(4, '0:0');
The following method returns the duration in seconds. So you could simply use that in moment.js
function getDurationInSecond(youtubeDuration)
{
var re=/pt([0-9]+)M([0-9]+)S/gi,
rex = new RegExp(re),
du = rex.exec(youtubeDuration);
if (du.length<1)
return 0;
var s=0;
s+= du.length >1 && du[1]? parseInt(du[1], 10) * 60 :0; // adding minute
s+= du.length >2 && du[2]? parseInt(du[1], 10) :0; //
return s;
}
var time='PT2M45S';
console.log(getDurationInSecond(time));
本文标签: javascriptHow to format the duration of YouTube API video using momentjsStack Overflow
版权声明:本文标题:javascript - How to format the duration of YouTube API video using moment.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745442380a2658504.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论