Initial commit
[yaffs-website] / node_modules / js-yaml / lib / js-yaml / type / timestamp.js
1 'use strict';
2
3 var Type = require('../type');
4
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
9
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
21
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;
26   return false;
27 }
28
29 function constructYamlTimestamp(data) {
30   var match, year, month, day, hour, minute, second, fraction = 0,
31       delta = null, tz_hour, tz_minute, date;
32
33   match = YAML_DATE_REGEXP.exec(data);
34   if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
35
36   if (match === null) throw new Error('Date resolve error');
37
38   // match: [1] year [2] month [3] day
39
40   year = +(match[1]);
41   month = +(match[2]) - 1; // JS month starts with 0
42   day = +(match[3]);
43
44   if (!match[4]) { // no hour
45     return new Date(Date.UTC(year, month, day));
46   }
47
48   // match: [4] hour [5] minute [6] second [7] fraction
49
50   hour = +(match[4]);
51   minute = +(match[5]);
52   second = +(match[6]);
53
54   if (match[7]) {
55     fraction = match[7].slice(0, 3);
56     while (fraction.length < 3) { // milli-seconds
57       fraction += '0';
58     }
59     fraction = +fraction;
60   }
61
62   // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
63
64   if (match[9]) {
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;
69   }
70
71   date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
72
73   if (delta) date.setTime(date.getTime() - delta);
74
75   return date;
76 }
77
78 function representYamlTimestamp(object /*, style*/) {
79   return object.toISOString();
80 }
81
82 module.exports = new Type('tag:yaml.org,2002:timestamp', {
83   kind: 'scalar',
84   resolve: resolveYamlTimestamp,
85   construct: constructYamlTimestamp,
86   instanceOf: Date,
87   represent: representYamlTimestamp
88 });