You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*!
  2. * time-stamp <https://github.com/jonschlinkert/time-stamp>
  3. *
  4. * Copyright (c) 2015-2017, Jon Schlinkert.
  5. * Released under the MIT License.
  6. */
  7. 'use strict';
  8. /**
  9. * Parse the given pattern and return a formatted
  10. * timestamp.
  11. *
  12. * @param {String} `pattern` Date pattern.
  13. * @param {Date} `date` Date object.
  14. * @return {String}
  15. */
  16. module.exports = function(pattern, date) {
  17. if (typeof pattern !== 'string') {
  18. date = pattern;
  19. pattern = 'YYYY:MM:DD';
  20. }
  21. if (!date) date = new Date();
  22. function timestamp() {
  23. var regex = /(?=(YYYY|YY|MM|DD|HH|mm|ss|ms))\1([:\/]*)/;
  24. var match = regex.exec(pattern);
  25. if (match) {
  26. var increment = method(match[1]);
  27. var val = '00' + String(date[increment[0]]() + (increment[2] || 0));
  28. var res = val.slice(-increment[1]) + (match[2] || '');
  29. pattern = pattern.replace(match[0], res);
  30. timestamp();
  31. }
  32. }
  33. timestamp(pattern);
  34. return pattern;
  35. };
  36. function method(key) {
  37. return ({
  38. YYYY: ['getFullYear', 4],
  39. YY: ['getFullYear', 2],
  40. // getMonth is zero-based, thus the extra increment field
  41. MM: ['getMonth', 2, 1],
  42. DD: ['getDate', 2],
  43. HH: ['getHours', 2],
  44. mm: ['getMinutes', 2],
  45. ss: ['getSeconds', 2],
  46. ms: ['getMilliseconds', 3]
  47. })[key];
  48. }