UNPKG

1.2 kBJavaScriptView Raw
1/**
2 * dateUtil.js deals with code that is time-related and date-related
3 *
4 */
5'use strict';
6
7// Sort the object {stat: {mtime}} against dates descendingly
8
9module.exports.sortByDate = function (list) {
10 if (!list) throw new Error('List is not given');
11 if (list.length === 1) return;
12
13 list.sort(function (a, b) {
14 if (!a.stat || !b.stat) throw new Error('List has no `stat` property');
15 if (!a.stat.mtime || !b.stat.mtime) throw new Error('List has no `mtime` property');
16
17 let keyA = new Date(a.stat.mtime),
18 keyB = new Date(b.stat.mtime);
19
20 // Compare the 2 dates
21 if (keyA < keyB) return 1;
22 if (keyA > keyB) return -1;
23 return 0;
24 });
25 return list;
26};
27
28// Parse date into (MM:DD HH:MM Year) format for output
29module.exports.parseDate = function (str) {
30 let date = new Date(str);
31
32 // Check for invalid date
33 if (isNaN(date.getTime())) throw new Error('Invalid Date');
34
35 if (date.getFullYear() == new Date().getFullYear()) {
36 // If it's the current year
37 return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
38 } else {
39 return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}, ${date.getFullYear()}`;
40 }
41};
\No newline at end of file