Passed
Push — master ( c6b313...ea8146 )
by Kyungmi
01:36
created

date-util.js ➔ ???   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 7
c 3
b 0
f 0
nc 4
dl 0
loc 15
rs 8.2222
nop 2
1
/**
2
 * Date Util functions
3
 *
4
 * @since 1.0.0
5
 */
6
7
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
 * @returns {*}
14
 */
15
exports.formatDates = (model, formatString) => {
16
  if (model instanceof Array) {
17
    for (let i = 0; i < model.length; i++) {
18
      model[i] = exports.formatDates(model[i], formatString);
19
    }
20
  } else if (model instanceof Date || model instanceof moment) {
21
    return exports.formatDate(model, formatString);
22
  } else if (model instanceof Object) {
23
    const keys = Object.keys(model);
24
    for (let i = 0; i < keys.length; i++) {
25
      model[keys[i]] = exports.formatDates(model[keys[i]], formatString);
26
    }
27
  }
28
  return model;
29
};
30
31
/**
32
 * Localize date
33
 * @param {Date} date
34
 * @param {number} [utcOffset]
35
 * @returns {moment}
36
 */
37
exports.toLocalDate = (date, utcOffset) => {
38
  return moment(date).utcOffset(typeof utcOffset === 'undefined' ? 9 : utcOffset);
39
};
40
41
/**
42
 * Format date to string
43
 * @param {Date} date
44
 * @param {string} [formatString]
45
 * @param {number} [utcOffset]
46
 * @returns {string}
47
 */
48
exports.formatDate = (date, formatString, utcOffset) => {
49
  return exports.toLocalDate(date, utcOffset).format(formatString);
50
};
51