To parse and manipulate dates using Moment.js in JavaScript, follow these steps:
Install Moment.js: Include the Moment.js library in your project by downloading it from the official website or by using a package manager like npm or yarn.
Import Moment.js: Import the Moment.js library into your JavaScript code using the require
or import
statement.
const moment = require('moment'); // If using CommonJS module system
// or
import moment from 'moment'; // If using ES modules
const myDate = moment("2022-01-01");
// Add or subtract time
const futureDate = moment().add(1, 'day');
const pastDate = moment().subtract(2, 'weeks');
// Set specific parts of a date
myDate.year(2023);
myDate.month(3); // 0-indexed, so 3 represents April
myDate.date(15);
// Format dates
const formattedDate = myDate.format('MMMM Do, YYYY'); // Output: "April 15th, 2023"
// Get the difference between two dates
const diffInDays = futureDate.diff(pastDate, 'days');
Moment.js also supports various operations like comparing dates, handling timezones, localizing dates, and much more. Check out the Moment.js documentation for additional features and examples: https://momentjs.com/docs/
Please note that Moment.js is a popular library. However, it is in maintenance mode and the Moment team recommends using modern alternatives like Luxon or Date-fns for new projects.