How to use moment.js instead of new date()?

Member

by orpha , in category: Javascript , 7 months ago

How to use moment.js instead of new date()?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 7 months ago

@orpha 

To use moment.js instead of the built-in new Date() constructor in JavaScript, you need to first include the moment.js library in your project. You can do this by adding a script tag to your HTML file pointing to the moment.js library file, or by installing moment.js through a package manager like npm.


Here is an example of how to create a new date using moment.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Include moment.js library
const moment = require('moment');

// Using moment.js instead of new Date()
const now = moment(); // creates a moment object representing the current date and time
console.log(now.format('MMMM Do YYYY, h:mm:ss a')); // Output: September 15th 2021, 3:45:33 pm

// You can also pass a date string or specific format to create a moment object
const date = moment('2021-12-25', 'YYYY-MM-DD');
console.log(date.format('dddd, MMMM Do YYYY')); // Output: Saturday, December 25th 2021


By using moment.js, you have access to a wide range of formatting options and manipulation methods that aren't available with the native Date object. Moment.js provides a more intuitive and flexible way to work with dates and times in JavaScript.