index.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*!
  2. * time-stamp <https://github.com/jonschlinkert/time-stamp>
  3. *
  4. * Copyright (c) 2015, Jon Schlinkert.
  5. * Licensed 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 timestamp(pattern, date) {
  17. if (typeof pattern !== 'string') {
  18. date = pattern;
  19. pattern = 'YYYY:MM:DD';
  20. }
  21. date = date || new Date();
  22. return pattern.replace(/([YMDHms]{2,4})(:\/)?/g, function(_, key, sep) {
  23. var increment = method(key);
  24. if (!increment) return _;
  25. sep = sep || '';
  26. var res = '00' + String(date[increment[0]]() + (increment[2] || 0));
  27. return res.slice(-increment[1]) + sep;
  28. });
  29. };
  30. function method(key) {
  31. return ({
  32. YYYY: ['getFullYear', 4],
  33. YY: ['getFullYear', 2],
  34. // getMonth is zero-based, thus the extra increment field
  35. MM: ['getMonth', 2, 1],
  36. DD: ['getDate', 2],
  37. HH: ['getHours', 2],
  38. mm: ['getMinutes', 2],
  39. ss: ['getSeconds', 2],
  40. ms: ['getMilliseconds', 3]
  41. })[key];
  42. }