首页 > 解决方案 > 覆盖 Date.prototype.toJSON 以解决 Angular 7 中的 TimeZone 问题

问题描述

我有一个 Angular 7 应用程序。我正在向我的服务器发送日期。但是由于时区,我的时间要提前 3 小时返回服务器。我了解到解决这个问题的唯一方法就是写作 Date.prototype.toJSON。但是,我不知道角度,我应该在哪里写下面的代码以及如何写?(例如 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();
}

堆栈闪电战

标签: angulartypescriptangular7

解决方案


您可以在您的应用程序的主入口点覆盖 Date 原型,在您的情况下是 AppModule.ts,因此它将可用于整个应用程序。

应用模块.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 => {});
  }  

这是分叉的stackblitz链接

希望这会有所帮助!


推荐阅读