Table of Contents
Formatting date in JavaScript isn't straightforward. Having different dates in different parts of the world makes it more complicated.
In this article, we will see how to print data in YYYY-MM-DD format in JavaScript.
Creating a date object
You can create a date object using the following code:
1const date = new Date()
Getting the full year
From the created date object, we can get the full year (in 4 digits) as shown below:
1const year = date.getFullYear()
Getting the month
Getting the month is a bit tricky. The month index starts with 0, hence for January, it will return 0, February as 1, and so on.
First, we need to add 1 to the month. Then we need to add 0 padding (convert 2 to 02), to fit all the months in MM
format.
1const month = (date.getMonth() + 1).toString().padStart(2, "0")
In the above code, we have converted the month to a string since padStart is a string method.
Getting the date
Date is straightforward, all we need to do is add 0 padding
1const paddedDate = date.getDate().toString().padStart(2, "0")
Printing date in YYYY-MM-DD format
Now we can combine the year, month, and date and print it.
1const date = new Date()2const year = date.getFullYear()3const month = (date.getMonth() + 1).toString().padStart(2, "0")4const paddedDate = date.getDate().toString().padStart(2, "0")5console.log(`${year}-${month}-${paddedDate}`)
Using libraries
If you want more formats, and you have a lot of date operations, then you can use one of the following libraries
Using date-fns
date-fns can be used to format the date as follows:
1const { format } = require("date-fns")2format(new Date(), "yyyy-MM-dd")
Using Luxon
You can format the Date using Luxon as shown below:
1const { DateTime } = require("luxon")2DateTime.now().toFormat("yyyy-LL-dd")
You can refer to the luxon documentation for more details.
Do follow me on twitter where I post developer insights more often!