9679b23933ea2ed3e285d85c51c9dd7ed580360f7301dd58401d2e70072ec6453787fa65852659f64d5251bddd196b1e98cd9f43acdcf8e33b230d65e484d2 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. 'use strict';
  2. var Type = require('../type');
  3. var YAML_DATE_REGEXP = new RegExp(
  4. '^([0-9][0-9][0-9][0-9])' + // [1] year
  5. '-([0-9][0-9])' + // [2] month
  6. '-([0-9][0-9])$'); // [3] day
  7. var YAML_TIMESTAMP_REGEXP = new RegExp(
  8. '^([0-9][0-9][0-9][0-9])' + // [1] year
  9. '-([0-9][0-9]?)' + // [2] month
  10. '-([0-9][0-9]?)' + // [3] day
  11. '(?:[Tt]|[ \\t]+)' + // ...
  12. '([0-9][0-9]?)' + // [4] hour
  13. ':([0-9][0-9])' + // [5] minute
  14. ':([0-9][0-9])' + // [6] second
  15. '(?:\\.([0-9]*))?' + // [7] fraction
  16. '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
  17. '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
  18. function resolveYamlTimestamp(data) {
  19. if (data === null) return false;
  20. if (YAML_DATE_REGEXP.exec(data) !== null) return true;
  21. if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
  22. return false;
  23. }
  24. function constructYamlTimestamp(data) {
  25. var match, year, month, day, hour, minute, second, fraction = 0,
  26. delta = null, tz_hour, tz_minute, date;
  27. match = YAML_DATE_REGEXP.exec(data);
  28. if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
  29. if (match === null) throw new Error('Date resolve error');
  30. // match: [1] year [2] month [3] day
  31. year = +(match[1]);
  32. month = +(match[2]) - 1; // JS month starts with 0
  33. day = +(match[3]);
  34. if (!match[4]) { // no hour
  35. return new Date(Date.UTC(year, month, day));
  36. }
  37. // match: [4] hour [5] minute [6] second [7] fraction
  38. hour = +(match[4]);
  39. minute = +(match[5]);
  40. second = +(match[6]);
  41. if (match[7]) {
  42. fraction = match[7].slice(0, 3);
  43. while (fraction.length < 3) { // milli-seconds
  44. fraction += '0';
  45. }
  46. fraction = +fraction;
  47. }
  48. // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
  49. if (match[9]) {
  50. tz_hour = +(match[10]);
  51. tz_minute = +(match[11] || 0);
  52. delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
  53. if (match[9] === '-') delta = -delta;
  54. }
  55. date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
  56. if (delta) date.setTime(date.getTime() - delta);
  57. return date;
  58. }
  59. function representYamlTimestamp(object /*, style*/) {
  60. return object.toISOString();
  61. }
  62. module.exports = new Type('tag:yaml.org,2002:timestamp', {
  63. kind: 'scalar',
  64. resolve: resolveYamlTimestamp,
  65. construct: constructYamlTimestamp,
  66. instanceOf: Date,
  67. represent: representYamlTimestamp
  68. });