angularangular-date-format

Format date in Angular based on Timezone


I'm receiving dates from my API that are in UTC format. I need to output the dates using the user's local timezone. Each user is assigned a timezone that I pull from a different API.

Using the following documentation I was able to make things work for all time zones with a + (i.e. +100, +200, etc.). However when I have a timezone with a - (i.e. -800). This does not work.

Works:

{{element.myDate | date:'d-MMM-yyyy HH:mm' : '+800' }}

Orginal Value: 7-Jan-2019 00:46

New Value: 7-Jan-2019 16:46

Does NOT Work (timezone is ignored):

{{element.myDate | date:'d-MMM-yyyy HH:mm' : '-800' }}

Orginal Value: 7-Jan-2019 00:46

New Value: 7-Jan-2019 00:46

Angular Class used after calling API

export class MyClass {
  constructor(
    public myDate: Date,
    public otherData: string
  ) {}
}

Solution

  • Since the date is considered as "local" in Angular, you can first convert it to UTC, and show the result in the view. The conversion method below assumes that a myUtcDate property is present in the element class:

    this.myUtcDate = new Date(Date.UTC(
      this.myDate.getFullYear(),
      this.myDate.getMonth(),
      this.myDate.getDate(),
      this.myDate.getHours(),
      this.myDate.getMinutes(),
      this.myDate.getSeconds()
    ));
    
    {{ element.myUtcDate | date:'d-MMM-yyyy HH:mm' : '-800' }}
    

    See this stackblitz for a demo.