Format a Date as a Year-Month-Day String in JavaScript

To format a date in YYYYMMDD or similar string format in JavaScript, we can use the following. In this example we use the current date.

Using dateformat:

$ npm install dateformat
const dateFormat = require('dateformat')

const now = new Date()
const dateString = dateFormat(now, 'yyyymmdd')

console.log(dateString)

Result:

20210313

Using moment.js:

$ npm install moment
const moment = require('moment')

const now = new Date()
const dateString = moment(now).format('YYYYMMDD')

console.log(dateString)

Result:

20210313

References

https://www.npmjs.com/package/dateformat

https://www.npmjs.com/package/moment

 

Leave a Reply

Your email address will not be published. Required fields are marked *