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

标签 angular typescript angular7

我有一个 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/

相关文章:

angular - 渲染器多个 selectRootElement 问题

javascript - typescript 值检查

javascript - 替换过滤数组上的元素

Angular 7 : Build Prod Error: Property 'value' does not exist on type 'Component'

Angular Material 对话框 - 将类型传递到对话框组件中

显示空行的 Angular Material 表

typescript - Angular 2 - 导入外部传单 typescript 库

angular - 如何使子页面的 ionic 标签可见?

javascript - Angular2 RxJS - 分割 url 集合以获取更小的 block

angular - 使用 set 将数据从父级传递给子级时如何解决 @input 装饰器的问题?