-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
59 lines (56 loc) · 1.32 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
'use strict';
function parseDuration(PT, format) {
var output = [];
var durationInSec = 0;
var matches = PT.match(/P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)W)?(?:(\d*)D)?T?(?:(\d*)H)?(?:(\d*)M)?(?:(\d*)S)?/i);
var parts = [
{ // years
pos: 1,
multiplier: 86400 * 365
},
{ // months
pos: 2,
multiplier: 86400 * 30
},
{ // weeks
pos: 3,
multiplier: 604800
},
{ // days
pos: 4,
multiplier: 86400
},
{ // hours
pos: 5,
multiplier: 3600
},
{ // minutes
pos: 6,
multiplier: 60
},
{ // seconds
pos: 7,
multiplier: 1
}
];
for (var i = 0; i < parts.length; i++) {
if (typeof matches[parts[i].pos] != 'undefined') {
durationInSec += parseInt(matches[parts[i].pos]) * parts[i].multiplier;
}
}
var totalSec = durationInSec;
// Hours extraction
if (durationInSec > 3599) {
output.push(parseInt(durationInSec / 3600));
durationInSec %= 3600;
}
// Minutes extraction with leading zero
output.push(('0' + parseInt(durationInSec / 60)).slice(-2));
// Seconds extraction with leading zero
output.push(('0' + durationInSec % 60).slice(-2));
if (format === undefined)
return output.join(':');
else if (format === 'sec')
return totalSec;
};
module.exports = parseDuration;