UNPKG

1.13 kBJavaScriptView Raw
1'use strict';
2
3const assert = require('assert');
4
5module.exports = function castDate(value) {
6 // Support empty string because of empty form values. Originally introduced
7 // in https://github.com/Automattic/mongoose/commit/efc72a1898fc3c33a319d915b8c5463a22938dfe
8 if (value == null || value === '') {
9 return null;
10 }
11
12 if (value instanceof Date) {
13 assert.ok(!isNaN(value.valueOf()));
14
15 return value;
16 }
17
18 let date;
19
20 assert.ok(typeof value !== 'boolean');
21
22 if (value instanceof Number || typeof value === 'number') {
23 date = new Date(value);
24 } else if (typeof value === 'string' && !isNaN(Number(value)) && (Number(value) >= 275761 || Number(value) < -271820)) {
25 // string representation of milliseconds take this path
26 date = new Date(Number(value));
27 } else if (typeof value.valueOf === 'function') {
28 // support for moment.js. This is also the path strings will take because
29 // strings have a `valueOf()`
30 date = new Date(value.valueOf());
31 } else {
32 // fallback
33 date = new Date(value);
34 }
35
36 if (!isNaN(date.valueOf())) {
37 return date;
38 }
39
40 assert.ok(false);
41};
\No newline at end of file