How to turn string to date using moment.js?

Member

by dedrick , in category: Javascript , a month ago

How to turn string to date using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , a month ago

@dedrick 

You can turn a string into a date using Moment.js by using the moment function with the string as the first argument and the format of the date as the second argument. Here's an example:

1
2
3
4
5
6
7
const moment = require('moment');

const dateString = '2022-10-15';
const dateFormat = 'YYYY-MM-DD';

const date = moment(dateString, dateFormat);
console.log(date); // Output: Sun Oct 15 2022 00:00:00 GMT+0000


In this example, we first include Moment.js in our code using require('moment'). We then create a string representation of a date in the dateString variable and specify its format in the dateFormat variable. We then use the moment function with the dateString and dateFormat as arguments to parse the string into a Moment object.