2

In my Angular 15 app, I am currently overriding the default time zone using an injection token method as suggested by Core Team.

It works as expected but here's the catch. I have edge case implementations where DatePipe is used directly on the component-side only, not through Angular text interpolation in HTML like {{ dateToDisplay | date : "dd MMM yyyy, hh:mm a"}}.

Instead, all of the date manipulations occur on the component-level via TypeScript and the injection token does not overwrite:

import { Component, OnInit} from "@angular/core";
import { DatePipe } from "@angular/common";

export class Angular15Component implements OnInit {
    dateToDisplay: string;

    ngOnInit(): void {
        this.dateToDisplay = new DatePipe("en-us").transform("2023-01-27T22:29:36.86826Z", "dd MMM yyyy, hh:mm a");
        console.log("date", date); // 27 Jan 2023, 02:29 PM (I expected an overwrite, not 02:29 PM)
    }
}

My question is how to install time zone '-1200' if referencing the Class directly in the component?

If possible, please stray from suggestions like employing another library like DateFNS or MomentJS. Thanks.

20230825 UPDATE:

I believe it can be done in this way...

this.dateToDisplay = new DatePipe("en-us").transform("2023-01-27T22:29:36.86826Z", "dd MMM yyyy, hh:mm a", "-1200");
markreyes
  • 1,249
  • 1
  • 13
  • 27

1 Answers1

0

Actually, there are different ways you can do that when using DatePipe class directly:

const date = '2023-01-27T22:29:36.86826Z';
const format = "dd MMM yyyy, hh:mm a";

new DatePipe("en-us", '-1200').transform(date, format);
new DatePipe("en-us", null, { dateFormat: format, timezone: '-1200' }).transform(date);
new DatePipe("en-us").transform(date, format, "-1200");

The result of all 3 transform calls above will be the same.

yurzui
  • 205,937
  • 32
  • 433
  • 399