How to get tomorrow’s date in a string format in JavaScript ?
In this article, we will see how to print tomorrow’s date in string representation using JavaScript.
To achieve this, we use the Date object and create an instance of it. After that by using the setDate() method, we increase one date to the present date. Now by using the getDate() method you will get tomorrow’s date. Now to convert that date to the string we use the string template literals, getFullYear, getMonth, padStart methods. Below is the implementation of this:
Example: In this example, we will get tomorrow’s date in the string format.
Javascript
<script>
const tomorrow = () => {
let d = new Date();
d.setDate(d.getDate() + 1);
let year = d.getFullYear()
let month = String(d.getMonth() + 1)
let day = String(d.getDate())
month = month.length == 1 ?
month.padStart( '2' , '0' ) : month;
day = day.length == 1 ?
day.padStart( '2' , '0' ) : day;
console.log(`${year}-${month}-${day}`);
}
tomorrow()
</script>
|
Output:
"2022-12-31"
Example 2: In this example, we will get the already given date into the string format.
Javascript
<script>
const tomorrow = (dt) => {
let d = new Date(dt);
d.setDate(d.getDate() + 1);
let year = d.getFullYear()
let month = String(d.getMonth() + 1)
let day = String(d.getDate())
month = month.length == 1 ?
month.padStart( '2' , '0' ) : month;
day = day.length == 1 ?
day.padStart( '2' , '0' ) : day;
console.log(`${year}-${month}-${day}`);
}
tomorrow( "2020-12-31" )
tomorrow( "2021-02-28" )
tomorrow( "2021-4-30" )
</script>
|
Output:
"2021-01-01"
"2021-03-01"
"2021-05-01"
Note: Enter the date in yyyy-mm-dd format.
Last Updated :
30 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...