Sahar
Sahar

Reputation: 111

How to get tomorrow's date of a specific date

I am trying to get tomorrow's date of a specific date using JavaScript in format (yyyy-mm-dd). For example the specific date is 2021-08-31 and I have got this script:

var date  = "2021-08-31"
date = new Date(date.split("-")[0],date.split("-")[1],date.split("-")[2]) 
date.setDate(date.getDate() + 1);
var tomorrows_date_month = date.getMonth()
var tomorrows_date_day = date.getDate()
var tomorrows_date_year = date.getFullYear()
console.log(tomorrows_date_year + "-" + tomorrows_date_month + "-" + tomorrows_date_day)

The expected output is:

2021-09-01

But the output of this code is :

2021-9-2

Upvotes: 0

Views: 147

Answers (3)

kshetline
kshetline

Reputation: 13682

new Date(new Date(date + 'T00:00Z').getTime() + 86400000).toISOString().substr(0, 10)

The added 'T00:00Z' assures the date is parsed as UTC, to match the UTC timezone used by toISOString(). Adding 86400000 (the number of milliseconds in one day) advances the date without having to fuss with the date field directly.

Upvotes: 0

Y.T.
Y.T.

Reputation: 2729

Internally js month is stored as a value between 0 and 11. So you need to minusdate.split("-")[1] by 1. Otherwise, javascript will think that your month is actually September and we know that "2021-09-32" is translated to "2021-10-2", therefore the date is shown as "2".

var date  = "2021-08-31"
date = new Date(date.split("-")[0],date.split("-")[1] - 1,date.split("-")[2]) 
date.setDate(date.getDate() + 1)
var tomorrows_date_month = date.getMonth() + 1
var tomorrows_date_day = date.getDate()
var tomorrows_date_year = date.getFullYear()
console.log(tomorrows_date_year + "-" + tomorrows_date_month + "-" + tomorrows_date_day)

Also note that date = new Date("2021-08-31") is enough for converting a string into a Date object.

Upvotes: 0

Alireza Ahmadi
Alireza Ahmadi

Reputation: 9893

First you don't need split "2021-08-31" to use as date parameter, so just use new Date("2021-08-31");

Second note that you need to use d.getMonth() + 1 and add leading zero if the length is less than 2:

Try this one:

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) 
        month = '0' + month;
    if (day.length < 2) 
        day = '0' + day;

    return [year, month, day].join('-');
}

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

var date  = "2021-08-31"

var date1 = new Date(date);

console.log(formatDate(date1.addDays(1)));

Upvotes: 2

Related Questions