Stop using Moment.js
As recommended by other great answers, in most cases it's best to use a library when dealing dates. However, it's important to know that as of September 2020 Moment.js is considered legacy and should no longer be used in new projects.
Quoting Moment's statement in their official docs:
We would like to discourage Moment from being used in new projects going forward. [...] We now generally consider Moment to be a legacy project in maintenance mode. It is not dead, but it is indeed done.
Recommended alternatives
Below are the alternatives recommended by Moment.
Luxon can be thought of as the evolution of Moment. It is authored by Isaac Cambron, a long-time contributor to Moment. Please read Why does Luxon exist? and the For Moment users pages in the Luxon documentation.
- Locales:
Intl
provided
- Time Zones:
Intl
provided
import {DateTime} from 'luxon'
function addMinutes(date, minutes) {
return DateTime.fromJSDate(date).plus({minutes}).toJSDate()
}
Day.js is designed to be a minimalist replacement for Moment.js, using a similar API. It is not a drop-in replacement, but if you are used to using Moment's API and want to get moving quickly, consider using Day.js.
- Locales: Custom data files that can be individually imported
- Time Zones:
Intl
provided, via a plugin
import dayjs from 'dayjs'
function addMinutes(date, minutes) {
return dayjs(date).add(minutes, 'minutes').toDate()
}
Date-fns offers a series of functions for manipulating JavaScript Date
objects. For more details, scroll to "Why date-fns?" on the date-fns home page.
- Locales: Custom data files that can be individually imported
- Time Zones:
Intl
provided, via a separate companion library
import {addMinutes} from 'date-fns'
function addMinutesDemo(date, minutes) {
return addMinutes(date, minutes)
}
js-Joda is a JavaScript port of Java's Three-Ten Backport, which is the base for JSR-310 implementation of the Java SE 8 java.time
package. If you are familiar with java.time
, Joda-Time, or Noda Time, you will find js-Joda comparable.
- Locales: Custom data files via add-on module
- Time Zones: Custom data files via add-on module
import {LocalDateTime, nativeJs, convert} from '@js-joda/core'
function addMinutes(date, minutes) {
return convert(
LocalDateTime.from(
nativeJs(date)
).plusMinutes(minutes)
).toDate()
}