我有一个 Angular 7 应用程序。我正在向我的服务器发送日期。但是由于时区,我的时间要提前 3 小时返回服务器。 我了解到解决这个问题的唯一方法是写 Date.prototype.toJSON
.但是,我不知道 Angular ,我应该在哪里写下面的代码以及如何写? (例如 index.html、app.module.ts、...)我在下面写了我的 stackblitz 示例。
Date.prototype.toJSON = function(key){
//This code return me as string like "25.02.0219 19:48:52"
return this.toLocaleDateString() + ' ' + this.toLocaleTimeString();
}
STACKBLITZ
最佳答案
您可以在您的应用程序的主入口点覆盖 Date 原型(prototype),在您的情况下是 AppModule.ts,因此它将可用于整个应用程序。
App.module.ts
export class AppModule {
constructor() {
this.overrideDate();
}
overrideDate() {
Date.prototype.toJSON = function (key) {
//This code return me as string like "25.02.0219 19:48:52"
return this.toLocaleDateString() + ' ' + this.toLocaleTimeString();
}
}
现在您可以在您的组件中使用它。
save() {
console.log(this.myForm.value);
this.http.post("localhost:5000",this.myForm.value).subscribe(result => {});
}
Here is forked stackblitz link
希望这会有所帮助!
关于angular - 覆盖 Date.prototype.toJSON 以解决 Angular 7 中的 TimeZone 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55064962/