3 var Type = require('../type');
5 var YAML_DATE_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
10 var YAML_TIMESTAMP_REGEXP = new RegExp(
11 '^([0-9][0-9][0-9][0-9])' + // [1] year
12 '-([0-9][0-9]?)' + // [2] month
13 '-([0-9][0-9]?)' + // [3] day
14 '(?:[Tt]|[ \\t]+)' + // ...
15 '([0-9][0-9]?)' + // [4] hour
16 ':([0-9][0-9])' + // [5] minute
17 ':([0-9][0-9])' + // [6] second
18 '(?:\\.([0-9]*))?' + // [7] fraction
19 '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
20 '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
22 function resolveYamlTimestamp(data) {
23 if (data === null) return false;
24 if (YAML_DATE_REGEXP.exec(data) !== null) return true;
25 if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
29 function constructYamlTimestamp(data) {
30 var match, year, month, day, hour, minute, second, fraction = 0,
31 delta = null, tz_hour, tz_minute, date;
33 match = YAML_DATE_REGEXP.exec(data);
34 if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
36 if (match === null) throw new Error('Date resolve error');
38 // match: [1] year [2] month [3] day
41 month = +(match[2]) - 1; // JS month starts with 0
44 if (!match[4]) { // no hour
45 return new Date(Date.UTC(year, month, day));
48 // match: [4] hour [5] minute [6] second [7] fraction
55 fraction = match[7].slice(0, 3);
56 while (fraction.length < 3) { // milli-seconds
62 // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
65 tz_hour = +(match[10]);
66 tz_minute = +(match[11] || 0);
67 delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
68 if (match[9] === '-') delta = -delta;
71 date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
73 if (delta) date.setTime(date.getTime() - delta);
78 function representYamlTimestamp(object /*, style*/) {
79 return object.toISOString();
82 module.exports = new Type('tag:yaml.org,2002:timestamp', {
84 resolve: resolveYamlTimestamp,
85 construct: constructYamlTimestamp,
87 represent: representYamlTimestamp