Handling converted date - adding 30 days gives invalid date error

Please refer to the following JSFiddle:

I’m trying to add 30 days to a converted date and it’s coming out to be an Invalid Date in the browsers’ console.log

function setStart(input) {
        if (!(input instanceof Date))
            console.log('Handling Date String:' +input)
            input = new Date(Date.parse(input));

        input.setHours(0);
        input.setMinutes(0);
        input.setSeconds(0);
        input.setMilliseconds(0);

        start = input;
        return start;        
    }
 
var initialDate = setStart('4/1/2021 00:00'); 
console.log("Printing converted date below:"); 
console.log(setStart('4/1/2021 00:00'));


var date = new Date(); // Now
//date.setDate(date.getDate() + 30); // Set now + 30 days as the new date
date.setDate(initialDate + 30);
console.log("Printing date after adding 30 days below")
console.log(date);

This is what browser’s console is printing:

 Handling Date String:4/1/2021 00:00
?editor_console=true:57 Printing converted date below:
?editor_console=true:57 Handling Date String:4/1/2021 00:00
?editor_console=true:57 Thu Apr 01 2021 00:00:00 GMT-0500 (Central Daylight Time)
?editor_console=true:57 Printing date after adding 30 days below
?editor_console=true:57 Invalid Date

What am I doing wrong here? I know I’m messing up with dates here.

Hi @Jack_Tauson_Sr, setDate() expects a number, so the line you commented out is correct:

date.setDate(date.getDate() + 30)

By just adding 30 to the date object OTOH, that date will first get converted to a string and then concatenated with the string "30" due to the funky JS type coercion rules; so you’ll get something like this:

"Sat Sep 24 2022 06:18:22 GMT+0200 (Central European Summer Time)30"
// ..............................................................^^

… which is indeed not a valid date string.

1 Like

Hey @m3g4p0p , Thanks.

So the following worked for me:

function setStart(input) {
        if (!(input instanceof Date))
            console.log('Handling Date String:' +input)
            input = new Date(Date.parse(input));

        input.setHours(0);
        input.setMinutes(0);
        input.setSeconds(0);
        input.setMilliseconds(0);

        start = input;
        return start;        
    }
 
var initialDate = setStart('4/1/2021 00:00'); 
console.log("Printing converted date below:"); 
console.log(setStart('4/1/2021 00:00'));

var date = new Date(initialDate); // Now
date.setDate(date.getDate() + 30);
console.log("Printing date after adding 30 days below")
console.log(date);

So basically it took the number of days out using date.getDate() from the converted date setStart('4/1/2021 00:00') and added 30 days to it. Here is my updated fiddle

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.