Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81149 views
1
'use strict';
2
3
var Type = require('../type');
4
5
var YAML_TIMESTAMP_REGEXP = new RegExp(
6
'^([0-9][0-9][0-9][0-9])' + // [1] year
7
'-([0-9][0-9]?)' + // [2] month
8
'-([0-9][0-9]?)' + // [3] day
9
'(?:(?:[Tt]|[ \\t]+)' + // ...
10
'([0-9][0-9]?)' + // [4] hour
11
':([0-9][0-9])' + // [5] minute
12
':([0-9][0-9])' + // [6] second
13
'(?:\\.([0-9]*))?' + // [7] fraction
14
'(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
15
'(?::([0-9][0-9]))?))?)?$'); // [11] tz_minute
16
17
function resolveYamlTimestamp(data) {
18
if (null === data) {
19
return false;
20
}
21
22
var match, year, month, day, hour, minute, second, fraction = 0,
23
delta = null, tz_hour, tz_minute, date;
24
25
match = YAML_TIMESTAMP_REGEXP.exec(data);
26
27
if (null === match) {
28
return false;
29
}
30
31
return true;
32
}
33
34
function constructYamlTimestamp(data) {
35
var match, year, month, day, hour, minute, second, fraction = 0,
36
delta = null, tz_hour, tz_minute, date;
37
38
match = YAML_TIMESTAMP_REGEXP.exec(data);
39
40
if (null === match) {
41
throw new Error('Date resolve error');
42
}
43
44
// match: [1] year [2] month [3] day
45
46
year = +(match[1]);
47
month = +(match[2]) - 1; // JS month starts with 0
48
day = +(match[3]);
49
50
if (!match[4]) { // no hour
51
return new Date(Date.UTC(year, month, day));
52
}
53
54
// match: [4] hour [5] minute [6] second [7] fraction
55
56
hour = +(match[4]);
57
minute = +(match[5]);
58
second = +(match[6]);
59
60
if (match[7]) {
61
fraction = match[7].slice(0, 3);
62
while (fraction.length < 3) { // milli-seconds
63
fraction += '0';
64
}
65
fraction = +fraction;
66
}
67
68
// match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
69
70
if (match[9]) {
71
tz_hour = +(match[10]);
72
tz_minute = +(match[11] || 0);
73
delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
74
if ('-' === match[9]) {
75
delta = -delta;
76
}
77
}
78
79
date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
80
81
if (delta) {
82
date.setTime(date.getTime() - delta);
83
}
84
85
return date;
86
}
87
88
function representYamlTimestamp(object /*, style*/) {
89
return object.toISOString();
90
}
91
92
module.exports = new Type('tag:yaml.org,2002:timestamp', {
93
kind: 'scalar',
94
resolve: resolveYamlTimestamp,
95
construct: constructYamlTimestamp,
96
instanceOf: Date,
97
represent: representYamlTimestamp
98
});
99
100