📜  npm i moment - Javascript (1)

📅  最后修改于: 2023-12-03 15:33:12.737000             🧑  作者: Mango

NPM i Moment - Javascript

Introduction

Moment.js is a popular library used for parsing, validating, manipulating, and formatting dates in JavaScript. It is an open-source project that has been widely adopted by developers worldwide. In this tutorial, we will show you how to install Moment.js using the npm package manager.

Prerequisites

Before getting started, make sure that you have Node.js and npm installed on your system. If you don't have it installed, head over to the official Node.js website to download it.

Installation

To install Moment.js, open your terminal or command prompt and type the following command:

npm i moment

This will install the latest version of Moment.js in your project. You can also install a specific version of the library by specifying its version number. For example,

npm i moment@2.24.0

This will install version 2.24.0 of the library.

Usage

Once installed, you can import Moment.js into your project using the following code:

const moment = require('moment');

This will give you access to the full Moment.js library and its features. For example, you can use Moment.js to format a date as a string:

const date = moment().format('MMMM Do YYYY, h:mm:ss a');
console.log(date);

Output:

June 10th 2022, 4:05:36 pm

You can also manipulate dates using Moment.js, for example, to add or subtract days, months, or years from a date:

const date = moment().add(1, 'days').subtract(2, 'months').year(2020);
console.log(date.format('MMMM Do YYYY, h:mm:ss a'));

Output:

March 9th 2020, 4:05:36 pm
Conclusion

Moment.js is a powerful, feature-packed library for working with dates in JavaScript. It makes it easy to parse, validate, manipulate, and format dates in any way you need. By following the steps outlined in this tutorial, you can quickly install and start using Moment.js in your projects.