date pipe angular 4 custom format with timezone (short)

mperle picture mperle · Jul 6, 2017 · Viewed 14.9k times · Source

I need to print timestamp custom format with timezone (short format):

{{ '2017-06-29 09:55:01.956-0400' | date:'MMM dd, y hh:mm a' }}

Output:

Jun 29, 2017 07:25 PM

But I need to append with timezone, for example:

Jun 29, 2017 07:25 PM IST

Angular provides timezone option with 'z' and 'Z' but none gave the expected result:

'MMM dd, y hh:mm a  z' ==> Jun 29, 2017 07:25 PM India Standard Time
'MMM dd, y hh:mm a  Z' ==> Jun 29, 2017 07:25 PM GMT+5:30

I want Jul 7, 2017, 12:27:01 AM IST.

Answer

Gosha_Fighten picture Gosha_Fighten · Jul 6, 2017

The DatePipe uses Intl to format dates. So, it's up to the system where your site is open to decide in what format the current timezone should be returned. To achieve the required behavior, I suggest you create a custom DatePipe that will return the required timezoe abbreviation. For example:

import { Pipe } from "@angular/core";
import { DatePipe } from "@angular/common";

@Pipe({
    name: "myDate",
    pure: true
})
export class MyDatePipe extends DatePipe {
    transform(value: any, pattern: string = "mediumDate"): string|null {
        let result = super.transform(value, pattern);
        result += " " + this.map[Intl.DateTimeFormat().resolvedOptions().timeZone];
        return result;
    }
    map = {
        "Asia/Calcutta": "IST"
    };
}

But, you will need to add each possible timezone to the map object. See the Plunker sample that illustrates this approach.