在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坏了吗?
您可能认为记录Date
会调用Date
对象的toString
函数,因此您可以覆盖它 - 但这不一定是真的。一些实现将为您提供类似于toISOString
而不是toString
的输出。在ECMAScript规范中没有任何地方定义console.log
应该如何表现。即使在the WhatWG Console Standard中,它也没有描述如何记录Date
对象 - 因此你处于依赖于实现的领域。
因此,不必覆盖Date
原型上的函数,你必须override the console.log
function,检查传递给它的参数是否是Date
,如果是这样,将其转换为字符串,然后将其传递给原始的console.log
函数。我会把这个留给你(或其他人)实施。
或者只是记得打电话给.toString()
,正如ChuongTran在答案中所示。
我认为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日星期二