覆盖Date.prototype.toJSON以解决angular 7中的TimeZone问题

时间:2019-03-08 14:11:00

标签: angular typescript angular7

我有一个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();
}

STACKBLITZ

1 个答案:

答案 0 :(得分:1)

在您的案例中,您可以在应用程序的主入口点重写Date原型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

希望这会有所帮助!