Skip to content

Instantly share code, notes, and snippets.

@alexilyaev
Last active October 31, 2023 19:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexilyaev/1369fa0f1cd83efbaf1d281009c5c084 to your computer and use it in GitHub Desktop.
Save alexilyaev/1369fa0f1cd83efbaf1d281009c5c084 to your computer and use it in GitHub Desktop.
Moment.js deprecated, date-fns issues

Moment.js is deprecated and date-fns issues

Synopsis

Moment.js is now considered a legacy project (see Moment.js Project Status).
Here's a comparison between the alternatives:

Issues with date-fns

new Date(2020, 0, 1).toISOString();
// "2019-12-31T22:00:00.000Z"
new Date(Date.UTC(2020, 0, 1)).toISOString();
// "2020-01-01T00:00:00.000Z"

// Passing a string has quirks:
// 'YYYY-MM-DD' (ISO date-only) is treated as UTC
new Date('2020-01-01').toISOString();
// "2020-01-01T00:00:00.000Z"

// 'YYYY-MM-DDTHH:mm:ss' (date-time) is treated as local time
new Date('2020-01-01T00:00:00').toISOString();
// "2019-12-31T22:00:00.000Z"

// Adding a time-zone will use that time-zone
new Date('2020-01-01T00:00:00Z').toISOString();
// "2020-01-01T00:00:00.000Z"
new Date('2020-01-01T00:00:00+00:00').toISOString();
// "2020-01-01T00:00:00.000Z"

// Get date values in UTC
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_components_and_time_zones
new Date('2020-01-01T00:00:00Z').getUTCHours();
// 0
new Date('2020-01-01T00:00:00Z').getUTCDate();
// 1

// We can adjust a date object in UTC:
const dateObj = new Date();
dateObj.setUTCFullYear(2020, 0, 1);
dateObj.setUTCHours(0, 0, 0, 0);
dateObj.toISOString();
// "2020-01-01T00:00:00.000Z"

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment