Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value for date keeps returning NaN

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?

like image 338
Obito Uchiha Avatar asked May 15 '26 16:05

Obito Uchiha


2 Answers

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}`);
like image 111
wentjun Avatar answered May 17 '26 04:05

wentjun


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);
like image 27
Maheer Ali Avatar answered May 17 '26 05:05

Maheer Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!