Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active March 13, 2019 19:21
Show Gist options
  • Save dfkaye/b985e08c9b5207810f5d02b440a0a110 to your computer and use it in GitHub Desktop.
Save dfkaye/b985e08c9b5207810f5d02b440a0a110 to your computer and use it in GitHub Desktop.
Couple of tests for date comparisons in JavaScript
// 13 March 2019
// https://inventi.studio/en/blog/why-you-shouldnt-use-moment-js
// Why is this so hard that anyone has to download 232kB for it?
function isBefore(a, b) {
return new Date(a) < new Date(b);
}
function sameDay(a, b) {
return new Date(a).getDay() === new Date(b).getDay();
}
var tests = [
{ a: 1552502239617, b: 1552502251455 },
{ a: "Wed Mar 13 2019 11:41:43 GMT-0700 (Pacific Daylight Time)", b: "Wed Mar 13 2019 11:42:15 GMT-0700 (Pacific Daylight Time)" },
{ a: new Date('1999', '11', '20'), b: new Date('1999', '11', '20')},
{ a: new Date('1999', '11', '20', '23', '59', '59'), b: new Date('1999', '11', '21', '0', '0', '0')}
];
console.log(tests.map(function(test) {
return isBefore.apply({}, [test.a, test.b]);
}));
// Array(4) [ true, true, false, true ]
console.log(tests.map(function(test) {
return sameDay.apply({}, [test.a, test.b]);
}));
// Array(4) [ true, true, true, false ]
// OK here...
console.log(new Date);
// Date 2019-03-13T19:17:01.544Z
// whereas moment().format() // > 2019-02-08T17:07:22+01:00
// But...
console.log(new Date(null));
// Date 1970-01-01T00:00:00.000Z
// whereas moment(null).format() // > Invalid date
console.log(new Date(undefined));
// Invalid Date
// whereas moment(undefined).format() // > 2019-02-08T17:07:22+01:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment