How to parse and manipulate dates using popular date libraries like Moment.js in JavaScript?

To parse and manipulate dates using Moment.js in JavaScript, follow these steps:

  1. 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.

  2. 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
  1. Parse a date: Use Moment.js to parse a date string into a Moment object. Moment.js supports various date formats, such as ISO 8601, timestamps, and custom formats.
const myDate = moment("2022-01-01");
  1. Manipulate dates: Moment.js provides a wide range of functions to manipulate and transform dates. Here are a few examples:
// 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.