Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Date.prototype.toJSON for solving TimeZone problem in angular 7

I have an angular 7 app. And I'm sending date to my server. But my time going to server 3 hour back because of time zone. And I learnt that only way for solving this problem is writing Date.prototype.toJSON . But, I don't know in angular, where should I write below code and how? (Forexample index.html, app.module.ts, ...) I wrote my stackblitz example at below.

Date.prototype.toJSON = function(key){
    //This code return me as string like "25.02.0219 19:48:52"
    return this.toLocaleDateString() + ' ' + this.toLocaleTimeString();
}

STACKBLITZ

like image 493
realist Avatar asked Mar 08 '19 14:03

realist


1 Answers

You can override Date prototype in the main entry point of your application in your case is AppModule.ts so it will be available to the whole application.

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();
    }

  }

Now you can in your component it will be available.

  save() {

    console.log(this.myForm.value);
    this.http.post("localhost:5000",this.myForm.value).subscribe(result => {});
  }  

Here is forked stackblitz link

Hope this will help!

like image 154
TheParam Avatar answered Nov 15 '22 07:11

TheParam