I want to have a variable having the current date as 'YYYY-MM-DD' format in Javascript. But when i execute my code and check it in the console.log. It simply says NaN
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
console.log("the date format here is ", + date);
The console.log shows the output like "the date format here is NaN"
Can anyone say what have is wrong here?
It is just :
console.log('the date format here is ', date);
There is no need for '+'
If you are thinking of using string concatenation using the plus operator, +, the right syntax would be
console.log('the date format here is ' + date);
However, when it comes to the scenario you are facing, I would personally perfer ES6's template literals.
console.log(`the date format here is ${date}`);
The problem is in passing the parameters to console.log(). You are passing two arguments to function and trying to covert second one which is date to Number using Unary Plus +
console.log("the date format here is ", + date);
Should be
console.log("the date format here is " + date);
You can use an array with contains methods as strings and then call them using map() and then join() them by -
var today = new Date();
var date = ['getFullYear','getMonth','getDate'].map(x => today[x]()).join('-')
console.log("the date format here is " + date);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With