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);
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?
Share Improve this question edited May 13, 2019 at 5:12 Titus 22.5k1 gold badge25 silver badges35 bronze badges asked May 13, 2019 at 5:08 Obito UchihaObito Uchiha 1131 silver badge10 bronze badges 1-
date
is a String like"2019-05-17"
...+"2019-05-17"
is not a number – Jaromanda X Commented May 13, 2019 at 5:10
4 Answers
Reset to default 6It 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 es 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);
remove the + sign or the, from its wrong
console.log("the date format here is ", + date);
Here is the correct one
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
console.log("the date format here is ", date);
You're using both a ma operator (for argument separation) and a plus operator. Use one:
console.log("the date format here is " + date);
Or the other:
console.log("the date format here is ", date);