index.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*!
  2. * time-stamp <https://github.com/jonschlinkert/time-stamp>
  3. *
  4. * Copyright (c) 2015-2018, Jon Schlinkert.
  5. * Released under the MIT License.
  6. */
  7. 'use strict';
  8. var dateRegex = /(?=(YYYY|YY|MM|DD|HH|mm|ss|ms))\1([:\/]*)/g;
  9. var timespan = {
  10. YYYY: ['getFullYear', 4],
  11. YY: ['getFullYear', 2],
  12. MM: ['getMonth', 2, 1], // getMonth is zero-based, thus the extra increment field
  13. DD: ['getDate', 2],
  14. HH: ['getHours', 2],
  15. mm: ['getMinutes', 2],
  16. ss: ['getSeconds', 2],
  17. ms: ['getMilliseconds', 3]
  18. };
  19. var timestamp = function(str, date, utc) {
  20. if (typeof str !== 'string') {
  21. date = str;
  22. str = 'YYYY-MM-DD';
  23. }
  24. if (!date) date = new Date();
  25. return str.replace(dateRegex, function(match, key, rest) {
  26. var args = timespan[key];
  27. var name = args[0];
  28. var chars = args[1];
  29. if (utc === true) name = 'getUTC' + name.slice(3);
  30. var val = '00' + String(date[name]() + (args[2] || 0));
  31. return val.slice(-chars) + (rest || '');
  32. });
  33. };
  34. timestamp.utc = function(str, date) {
  35. return timestamp(str, date, true);
  36. };
  37. module.exports = timestamp;