Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Can';t覆盖node.js中的Date to字符串_Node.js_Date_Overriding_Tostring - Fatal编程技术网

Can';t覆盖node.js中的Date to字符串

Can';t覆盖node.js中的Date to字符串,node.js,date,overriding,tostring,Node.js,Date,Overriding,Tostring,在node.js中: Date.prototype.toString = function dateToString() { return `${this.getMonth()}/${this.getDate()} of ${this.getFullYear()}` }; console.log("====>", new Date(2019, 0, 1)) 我希望是“2019年2月11日”,而不是“2019-01-01T02:00:00.000Z” node.js坏了吗?我认为node

在node.js中:

Date.prototype.toString = function dateToString() {
 return `${this.getMonth()}/${this.getDate()} of ${this.getFullYear()}`
};
console.log("====>", new Date(2019, 0, 1))
我希望是“2019年2月11日”,而不是“2019-01-01T02:00:00.000Z”


node.js坏了吗?

我认为node.js没有坏。但您需要调用toString()以在console.log中获取字符串

 Date.prototype.toString = function dateToString() {
  return `${this.getMonth()}/${this.getDate()} of ${this.getFullYear()}`
 };
 var date = new Date(2019, 0, 1);
 console.log("====>", date.toString());
 console.log("====>", date.toDateString());
输出:

=>2019年的0/1


==>2019年1月1日星期二

我认为node.js没有损坏。但您需要调用toString()以在console.log中获取字符串

 Date.prototype.toString = function dateToString() {
  return `${this.getMonth()}/${this.getDate()} of ${this.getFullYear()}`
 };
 var date = new Date(2019, 0, 1);
 console.log("====>", date.toString());
 console.log("====>", date.toDateString());
输出:

=>2019年的0/1


==>2019年1月1日星期二

您可能会认为记录
日期会调用
日期
对象的
toString
函数,因此您可以直接覆盖它-但这不一定是真的。一些实现将为您提供类似于
toISOString
的输出,而不是
toString
。ECMAScript规范中没有定义
console.log
的行为方式。即使在中,它也没有描述如何记录
Date
对象,因此您处于依赖于实现的领域

因此,您必须检查传递给它的参数是否是
日期
,而不是重写
日期
原型上的函数,如果是,则将其转换为字符串,然后将其传递给原始的
控制台.log
函数。我会让你(或其他人)来实施


或者只记得调用
.toString()
,正如Chungtran在他们的回答中所示。

您可能认为记录
日期会调用
日期对象的
toString
函数,所以您可以直接覆盖它-但这不一定是真的。一些实现将为您提供类似于
toISOString
的输出,而不是
toString
。ECMAScript规范中没有定义
console.log
的行为方式。即使在中,它也没有描述如何记录
Date
对象,因此您处于依赖于实现的领域

因此,您必须检查传递给它的参数是否是
日期
,而不是重写
日期
原型上的函数,如果是,则将其转换为字符串,然后将其传递给原始的
控制台.log
函数。我会让你(或其他人)来实施


或者记得调用
.toString()
,正如ChuongTran在回答中所示。

谢谢Matt,在Java背景下,我错误地期望Console.log会模仿System.println…谢谢Matt,在Java背景下,我错误地期望Console.log会模仿System.println。。。