Moment.js
lastmod 2024-01-26created 2018-08-3112 edits
| WARNING |
| Moment is considered a legacy project in maintenance mode. For time-related libraries, use Luxon, Day.js, date-fns, js-Joda, or JavaScript:Date, JavaScript:Temporal, or implement it yourself. For details, see here. For a Korean-language write-up, see Why you shouldn't use moment.js. |
Parse, validate, manipulate, and display dates and times in JavaScript.
Moment Timezone
Timezone library for Moment. See that page for details.
How to install
Printing after timezone conversion
import moment from 'moment-timezone';
export function iso8601ToLocal(text: string) {
if (text) {
return moment(text).tz(moment.tz.guess()).format('LLLL');
} else {
return '';
}
}
export function iso8601ToLocalDate(text?: string) {
if (text) {
return moment(text).tz(moment.tz.guess()).format('YYYY-MM-DD');
} else {
return '';
}
}
Changing the locale
Examples
Format Dates
moment().format('MMMM Do YYYY, h:mm:ss a'); // October 8th 2021, 9:55:17 am
moment().format('dddd'); // Friday
moment().format("MMM Do YY"); // Oct 8th 21
moment().format('YYYY [escaped] YYYY'); // 2021 escaped 2021
moment().format(); // 2021-10-08T09:55:17+09:00
Relative Time
moment("20111031", "YYYYMMDD").fromNow(); // 10 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 9 years ago
moment().startOf('day').fromNow(); // 10 hours ago
moment().endOf('day').fromNow(); // in 14 hours
moment().startOf('hour').fromNow(); // an hour ago
Calendar Time
moment().subtract(10, 'days').calendar(); // 09/28/2021
moment().subtract(6, 'days').calendar(); // Last Saturday at 9:55 AM
moment().subtract(3, 'days').calendar(); // Last Tuesday at 9:55 AM
moment().subtract(1, 'days').calendar(); // Yesterday at 9:55 AM
moment().calendar(); // Today at 9:55 AM
moment().add(1, 'days').calendar(); // Tomorrow at 9:55 AM
moment().add(3, 'days').calendar(); // Monday at 9:55 AM
moment().add(10, 'days').calendar(); // 10/18/2021
Multiple Locale Support
moment.locale(); // en
moment().format('LT'); // 9:55 AM
moment().format('LTS'); // 9:55:17 AM
moment().format('L'); // 10/08/2021
moment().format('l'); // 10/8/2021
moment().format('LL'); // October 8, 2021
moment().format('ll'); // Oct 8, 2021
moment().format('LLL'); // October 8, 2021 9:55 AM
moment().format('lll'); // Oct 8, 2021 9:55 AM
moment().format('LLLL'); // Friday, October 8, 2021 9:55 AM
moment().format('llll'); // Fri, Oct 8, 2021 9:55 AM
See also
Favorite site
Pages that link here