Angular 4 date pipe displays wrong date because of time zones - how to fix this?

前端 未结 3 1061
[愿得一人]
[愿得一人] 2020-11-29 03:24

I have a date value in each of my objects that I can Print like this:

 {{competition.compStart }}

And here is how it l

相关标签:
3条回答
  • 2020-11-29 03:51

    I also faced the same problem. before saving data convert the date format to the one used in service.For example in my case in Java it was 'YYYY-MM-DD'.So in angular just before saving all the data: where birthdate is binded to your template field or is simply displayed.

    this.birthdate= this.datePipe.transform(birthDate, 'yyyy-MM-dd'); where birthdate is not a date object but a string date.

    Now, when you need to show the date on the UI use:

                    let dd = (new Date(data.birthDate)).getUTCDate().toString();
    
                    let mm = ((new Date(data.birthDate)).getMonth()).toString();
                    let yy = (new Date(data.birthDate)).getFullYear().toString();
    
                    this.birthDate = new Date(Number(yy), Number(mm), Number(dd));
    
    0 讨论(0)
  • 2020-11-29 03:52

    for angular 5 and up , you can try to add timezone in pipe,

    By default it takes the local timezone of user machine

    and you can specify it in minutes for example for GMT-2, timezone: '-120'

    {{ competition.compStart | date: 'short' : '-120'}}
    
    0 讨论(0)
  • 2020-11-29 03:59

    Behind the scenes, DatePipe uses locale to display date in user's timezone. Try with client's timezone data:

    1931-05-31T00:00:00.000-0300 instead of 1931-05-31T00:00:00.000+0000.

    You can get client's offset in minutes using (new Date()).getTimezoneOffset()

    This is actually the known issue/limitation of DatePipe. Community is aware of it. It the future, you will be able to specify timezone as one of parameters ({{ value | date:format:zone }}).

    Here is the issue on github: https://github.com/angular/angular/issues/9324

    For more advanced date manipulations, I recommend moment.js (less headaches, better consistency, less testing, simpler maintaining).

    EDIT: It has been added:

    date_expression | date[:format[:timezone[:locale]]]

    Code: https://github.com/angular/angular/blob/5.0.4/packages/common/src/pipes/date_pipe.ts#L137 Docs: https://angular.io/api/common/DatePipe

    0 讨论(0)
提交回复
热议问题