aboutsummaryrefslogtreecommitdiff
path: root/node_modules/time-stamp/index.js
blob: 1a400adc1480621588a6efa9c5cf75577f745b69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*!
 * time-stamp <https://github.com/jonschlinkert/time-stamp>
 *
 * Copyright (c) 2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

/**
 * Parse the given pattern and return a formatted
 * timestamp.
 *
 * @param  {String} `pattern` Date pattern.
 * @param  {Date} `date` Date object.
 * @return {String}
 */

module.exports = function timestamp(pattern, date) {
  if (typeof pattern !== 'string') {
    date = pattern;
    pattern = 'YYYY:MM:DD';
  }
  date = date || new Date();
  return pattern.replace(/([YMDHms]{2,4})(:\/)?/g, function(_, key, sep) {
    var increment = method(key);
    if (!increment) return _;
    sep = sep || '';

    var res = '00' + String(date[increment[0]]() + (increment[2] || 0));
    return res.slice(-increment[1]) + sep;
  });
};

function method(key) {
  return ({
   YYYY: ['getFullYear', 4],
   YY: ['getFullYear', 2],
   // getMonth is zero-based, thus the extra increment field
   MM: ['getMonth', 2, 1],
   DD: ['getDate', 2],
   HH: ['getHours', 2],
   mm: ['getMinutes', 2],
   ss: ['getSeconds', 2],
   ms: ['getMilliseconds', 3]
  })[key];
}