Can';t覆盖node.js中的Date to字符串
在node.js中: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
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。。。