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

Member

by jerad , in category: Javascript , a year 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 , a year 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.

Related Threads:

How to validate a string has a proper day month and year with moment.js?
How to parse date string with '0' day to date in moment.js?
How to get year and month into number oracle?
How to get the next day skipping the weekend using moment.js?
How to combine day, month, year fields into a date in presto?
How to turn string to date using moment.js?