How to get date string from day number and month number using moment.js?

Member

by jerad , in category: Javascript , 8 months ago

How to get date string from day number and month number using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 8 months ago

@jerad 

You can use Moment.js to create a date string from the day number and month number by providing the day and month as arguments in the moment() function and then formatting the date string using the format() function.


Here's an example code snippet that shows how to achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const moment = require('moment');

// Day number and month number
const day = 15;
const month = 6; // 6 represents July

// Create a moment object with the provided day and month
const date = moment({ day, month });

// Format the date string
const dateString = date.format('YYYY-MM-DD');

console.log(dateString); // Output: 2021-07-15


In this code snippet, we create a moment object with the provided day and month using the moment() function. We then format the date string using the format('YYYY-MM-DD') function to get the date in the desired format.