date.js 1.1 KB

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