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 badges
Add a ment  | 

3 Answers 3

Reset to default 4

You 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