无法覆盖node.js中的Date toString

问题描述 投票:0回答:2

在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 date override tostring
2个回答
0
投票

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

因此,不必覆盖Date原型上的函数,你必须override the console.log function,检查传递给它的参数是否是Date,如果是这样,将其转换为字符串,然后将其传递给原始的console.log函数。我会把这个留给你(或其他人)实施。

或者只是记得打电话给.toString(),正如ChuongTran在答案中所示。


0
投票

我认为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日星期二

© www.soinside.com 2019 - 2024. All rights reserved.