How to add and format date in moment.js?

by scotty_walker , in category: Javascript , 5 months ago

How to add and format date in moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 5 months ago

@scotty_walker 

To add and format dates in Moment.js, you can follow these steps:

  1. Install Moment.js by including the Moment.js library in your project. You can include it via a
  2. Import Moment.js into your JavaScript file, either by adding to your HTML file or using import moment from 'moment' in your JavaScript file if you are using a module bundler like webpack.
  3. Create a new Moment object by calling the moment() function with the date and time you want to format. For example, to format the current date and time, you can use let now = moment();.
  4. Use the available formatting options provided by Moment.js to customize your date and time representation. Some common formatting options include: format('YYYY-MM-DD') to display the date in the 'YYYY-MM-DD' format (e.g., '2022-01-01'). format('MMM DD, YYYY') to display the date in the 'MMM DD, YYYY' format (e.g., 'Jan 01, 2022'). format('h:mm a') to display the time in the 'h:mm a' format (e.g., '9:30 am'). You can find a complete list of formatting options in the Moment.js documentation.


Here's an example that demonstrates adding and formatting a date in Moment.js:

1
2
3
4
5
6
const now = moment(); // Create a new Moment object with the current date and time
const formattedDate = now.format('YYYY-MM-DD'); // Format the date as 'YYYY-MM-DD'
console.log(formattedDate); // Output: 2022-01-01

const formattedDateTime = now.format('MMM DD, YYYY h:mm a'); // Format the date and time as 'MMM DD, YYYY h:mm a'
console.log(formattedDateTime); // Output: Jan 01, 2022 9:30 am


Remember to refer to the Moment.js documentation for more formatting options and advanced usage.