date pipe angular 4 custom format with timezone (short)

15,044

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.

Share:
15,044
mperle
Author by

mperle

Updated on June 25, 2022

Comments

  • mperle
    mperle almost 2 years

    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.

  • mperle
    mperle almost 7 years
    yes that helps. Thank you. Lets see whether angular team updates with a shorter timezone format in the upcoming releases..!!
  • Gosha_Fighten
    Gosha_Fighten almost 7 years
    I don't think that this will be even implemented since this does nor depend on Angular but rather to system settings. They may be different based on your browser and OS. So, you may have different results.
  • dileep balineni
    dileep balineni almost 3 years
    is there any way to use daylight saving