📜  npm moment (1)

📅  最后修改于: 2023-12-03 14:44:46.676000             🧑  作者: Mango

NPM Moment

NPM Moment is a JavaScript library that simplifies and handles dates and times in JavaScript. Moment.js makes it easy to work with dates, parse and format them, and compare them with other dates.

Installation
npm install moment
Usage

Once you have installed Moment using npm, you can use it in your JavaScript code like this:

const moment = require('moment');

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

This code will output the current date and time in the format of "Month day-of-month Year, hour:minute:second am/pm", for example "June 12th 2021, 10:30:00 am".

Formatting

Moment.js provides various formatting options that allow you to customize the output for dates and times. Here are a few examples:

moment().format('MMMM Do YYYY, h:mm:ss a');    // June 12th 2021, 10:30:00 am
moment().format('dddd');                      // Saturday
moment().format("MMM Do YY");                 // Jun 12th 21
moment().format('YYYY [escaped] YYYY');       // 2021 escaped 2021
moment().format();                            // 2021-06-12T10:30:00+05:30

You can find more about formatting options in the Moment.js documentation.

Parsing

Moment.js also allows you to parse dates and times from strings. Here's an example:

const date = moment('2021-06-12');
console.log(date.format('MMMM Do YYYY'));

This will output "June 12th 2021".

Manipulating Dates & Times

Moment.js provides many methods for manipulating dates and times. One example is adding or subtracting time:

const tomorrow = moment().add(1, 'day');
const yesterday = moment().subtract(1, 'day');

You can also set or get specific parts of a date or time:

const day = moment('2021-06-12');
day.year();   // 2021
day.month();  // 5
day.date();   // 12
day.hour();   // 0
day.minute(); // 0
day.second(); // 0
Conclusion

Moment.js is a powerful library that can simplify working with dates and times in JavaScript. Whether you need to format, parse, or manipulate dates, Moment.js makes it easy. So next time you're working with dates and times in JavaScript, give Moment.js a try!