日期管道 angular 4 带时区的自定义格式(短)

date pipe angular 4 custom format with timezone (short)

我需要打印带时区的时间戳自定义格式(短格式):

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

输出:

Jun 29, 2017 07:25 PM

但我需要附加时区,例如:

Jun 29, 2017 07:25 PM IST

Angular 为 'z''Z' 提供了时区选项,但 none 给出了预期的结果:

'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

我要Jul 7, 2017, 12:27:01 AM IST.

DatePipe 使用 Intl 来格式化日期。因此,由您的网站打开的系统来决定当前时区的格式 return。要实现所需的行为,我建议您创建一个自定义 DatePipe,它将 return 所需的 timezoe 缩写。例如:

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"
    };
}

但是,您需要将每个可能的时区添加到 map 对象。请参阅说明此方法的 Plunker sample