Using Native JavaScript Date and String Methods
One way to get a JavaScript date into a string in YYYYMMDD format is to use native JavaScript date and string methods.
For instance, we can write:
const date = new Date(2021, 1, 1)
const year = date.getFullYear()
const month = ('0' + (date.getMonth() + 1)).substr(-2)
const day = ('0' + date.getDate()).substr(-2)
const dateStr = [year, month, day].join('')
console.log(dateStr)
We create a date
object with the Date
constructor with the year, month, and day.
The month’s value is from 0 to 11, where 0 is for January, 1 for February, etc.
Then we can get the year, month, and day from the date.
We call getFullYear
to get the 4 digit year.
And we call getMonth
to get the month plus 1 to get a human-readable month.
Then we attach string 0 before it and call substr
-2 to get the last 2 characters of the string.
And we call getDate
to get the date and format it the same way with substr
.
Finally, we join the year
, month
, and day
together with join
.
Therefore, dateStr
is '20210201'
.
Date.prototype.toISOString
We can call toISOString
to get the date string from a JavaScript date object.
Then we can use string methods to extract the year, month, and date parts and remove the dashes from that part.
For instance, we can write:
const date = new Date(2021, 1, 1)
const dateStr = date.toISOString().slice(0, 10).replace(/-/g, "");
console.log(dateStr)
We call toISOString
to get the date string in ISO8601 format.
Then we call slice
with 0 and 10 to extract the first part, which has the year, month, and day.
And then we call replace
to replace all the dashes with empty strings to remove them.
Therefore, we get the same result for dateStr
.
Also, we can replace slice
with substring
:
const date = new Date(2021, 1, 1)
const dateStr = date.toISOString().substring(0, 10).replace(/-/g, "");
console.log(dateStr)
moment.js
We can also use the moment.js library to format a date easily.
For instance, we can write:
const date = new Date(2021, 1, 1)
const dateStr = moment(date).format('YYYYMMDD');
console.log(dateStr)
We pass in our date
to the moment
function to create a moment object withn the date.
Then we call format
with the format string to format the item.
And so we get the same value for dateStr
.
Conclusion
We can format a native JavaScript date into a string with native JavaScript date and string methods.
Or we can use moment.js to format a date.