[英]Value for date keeps returning NaN
I want to have a variable having the current date as 'YYYY-MM-DD' format in Javascript. 我希望在Javascript中有一个当前日期为'YYYY-MM-DD'格式的变量。 But when i execute my code and check it in the console.log.
但是,当我执行我的代码并在console.log中检查它。 It simply says NaN
它简单地说是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" console.log显示输出,如“这里的日期格式是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 如果您正在考虑使用plus运算符
+
来使用字符串连接,那么正确的语法就是
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 . 但是,当涉及到您所面临的场景时,我个人会更喜欢ES6的模板文字 。
console.log(`the date format here is ${date}`);
You're using both a comma 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);
The problem is in passing the parameters to console.log()
. 问题是将参数传递给
console.log()
。 You are passing two arguments to function and trying to covert second one which is date
to Number
using Unary Plus +
您正在传递两个参数的功能,并试图隐蔽第二个这是
date
对Number
使用一元加号+
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 -
您可以使用包含方法作为字符串的数组,然后使用
map()
调用它们,然后通过以下方式join()
它们-
var today = new Date(); var date = ['getFullYear','getMonth','getDate'].map(x => today[x]()).join('-') console.log("the date format here is " + date);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.