Borislav Hadzhiev
Tue Jan 25 2022·2 min read
Photo by Brannon Naito
To get tomorrow's date formatted as YYYY-MM-DD
:
getFullYear
, getMonth
and getDate
methods to get the year,
month and date.YYYY-MM-DD
.const date = new Date(); date.setDate(date.getDate() + 1); // 👇️ Tomorrow's date console.log(date); // 👇️ Format as YYYY-MM-DD function padTo2Digits(num) { return num.toString().padStart(2, '0'); } function formatDate(date) { return [ date.getFullYear(), padTo2Digits(date.getMonth() + 1), padTo2Digits(date.getDate()), ].join('-'); } // 👇️ 2022-01-26 (yyyy-mm-dd) (today is 2022-01-25) console.log(formatDate(date));
We used the Date() constructor to get the current date.
The setDate() method enables us to change the day of the month for the given date.
The
getDate
method returns the current day of the month, so all we have to do is add 1
to
the result.
The next step is to format tomorrow's date as YYYY-MM-DD
.
The padTo2Digits
function takes care of adding a leading zero if the month or
day only contain a single digit (are less than 10
).
function padTo2Digits(num) { return num.toString().padStart(2, '0'); } console.log(padTo2Digits(3)); // 👉️ '03' console.log(padTo2Digits(6)); // 👉️ '06' console.log(padTo2Digits(10)); // 👉️ '10'
We want to make sure that the result is always consistent and has 2 digits for the months and days, so we used the padStart method.
padTo2Digits
function is the total length of the string, so it will never pad the day or month if they already have 2 digits.The formatDate()
function formats the date as YYYY-MM-DD
.
The function makes use of the following 3 date-related methods.
Date.getFullYear method - returns a four-digit number representing the year that corresponds to a date.
Date.getMonth -
returns an integer between 0
(January) and 11
(December) and represents
the month for a given date. Yes, unfortunately the getMonth
method is off
by 1
.
Date.getDate -
returns an integer between 1
and 31
representing the day of the month for
a specific date.
getMonth
method returns a zero-based month index from 0 to 11, meaning January is 0
and December is 11
.Because the getMonth
method is zero-based we added 1 to its return value.
The last step is to place the calls to the methods in an array, so we can join them by a hyphen separator. Here are some examples.
console.log(['2022', '04', '21'].join('-')); // 👉️ '2022-04-21' console.log(['2023', '06', '19'].join('-')); // 👉️ '2023-06-19'
This gets us the date, formatted as yyyy-mm-dd
.
You could use this approach to format the date in different ways.