3

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
  • 3,342
  • 8
  • 20
  • 34
  • Could you elaborate on "didn't give expected result"? Is it showing the incorrect timezone or not showing at all? Adding `Z` seems to provide the correct timezone demonstrated by this [plunkr](https://plnkr.co/edit/9SgW9ClyZTqMMdR66Zgm?p=preview). It matched my timezone exactly in the 3 character format. – Alexander Staroselsky Jul 06 '17 at 19:16
  • edited question. Please check. Thanks. – mperle Jul 06 '17 at 19:22
  • I think you would need to write your own date formatting pipe to handle this. It could return a value using the existing pipe for the date/time format and then manipulate the timezone to return the 3 digit version instead of the full text. – Stephen R. Smith Jul 06 '17 at 19:55

1 Answers1

5

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.

Gosha_Fighten
  • 3,838
  • 1
  • 20
  • 31
  • yes that helps. Thank you. Lets see whether angular team updates with a shorter timezone format in the upcoming releases..!! – mperle Jul 07 '17 at 17:57
  • 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. – Gosha_Fighten Jul 07 '17 at 22:13
  • is there any way to use daylight saving – dileep balineni Jun 09 '21 at 14:28