Search code examples
angulartypescriptdatetimetimelocaltime

Angular2 Time incorrect when I insert a record. How can I impost GTM+2.00?


In my app I have a page were can insert a record with a property 'performedOn'. when insert record whit a date(24/07), the time is 00.00am but the GTM is -2.00 infact when save, date change in (23/07 at 22.00pm). How can I change time?? Thank!!!


Solution

  • You need to change the locale or just the timezone.

    • You can change the locale or timezone of your current date object and transform it manually to your needs by using a DatePipe.

    First you need to import DatePipe in your app.module file

    import { DatePipe } from '@angular/common';
    

    Add it to the providers in @NgModule.

    providers: [DatePipe]
    

    In component.ts:

    Import into the component.

    import { DatePipe } from '@angular/common';
    

    Add it to the constructor.

    constructor(private datePipe: DatePipe){}
    

    Then you can do something like this. This would transform the date to the timezone GMT+2.00.

    dateObject = new Date();
    
    formattedDate = this.datePipe.transform(this.dateObject, 'full', '+200');
    

    You can see the example live here.

    To clarify. DatePipe has 3 arguments (format, timezone, locale) and you can call them like this.

    this.myPipe.transform(myData, arg1, arg2, arg3)
    

    You can also format with the Pipe in the html like this:

    {{ myData | myPipe: 'arg1':'arg2':'arg3'... }}
    

    So to make the right date format you can play around with the arguments.

    If you want to make global changes you can check: