src/common/date-util.js   A
last analyzed

Complexity

Total Complexity 9
Complexity/F 1.8

Size

Lines of Code 40
Function Count 5

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 40
rs 10
c 0
b 0
f 0
ccs 13
cts 13
cp 1
wmc 9
mnd 4
bc 4
fnc 5
bpm 0.8
cpm 1.8
noi 0
1
/**
2
 * Date Util functions
3
 *
4
 * @since 1.0.0
5
 */
6
7 5
const moment = require('moment');
8
9
/**
10
 * Format all dates in the received model
11
 * @param {Array|Date|Object} model
12
 * @param {string} [formatString]
13
 * @param {number} [utcOffset]
14
 * @returns {*}
15
 */
16 5
exports.formatDates = (model, formatString, utcOffset) => {
17 260
  if (model instanceof Array) {
18 61
    return model.map(item => exports.formatDates(item, formatString, utcOffset));
19
  }
20 230
  if (model instanceof Date || model instanceof moment) {
21 67
    return exports.formatDate(model, formatString, utcOffset);
22
  }
23 163
  if (model instanceof Object) {
24 30
    const result = {};
25 182
    Object.keys(model).forEach((key) => { result[key] = exports.formatDates(model[key], formatString, utcOffset); });
26 30
    return result;
27
  }
28 133
  return model;
29
};
30
31
/**
32
 * Localize date
33
 * @param {Date} date
34
 * @param {number} [utcOffset]
35
 * @returns {moment}
36
 */
37 67
exports.toLocalDate = (date, utcOffset) => moment(date).utcOffset(typeof utcOffset === 'undefined' ? 9 : utcOffset);
38
39
/**
40
 * Format date to string
41
 * @param {Date} date
42
 * @param {string} [formatString]
43
 * @param {number} [utcOffset]
44
 * @returns {string}
45
 */
46
exports.formatDate = (date, formatString, utcOffset) => exports.toLocalDate(date, utcOffset).format(formatString);
47