【问题标题】:date pipe angular 4 custom format with timezone (short)带有时区的日期管道角度 4 自定义格式(短)
【发布时间】:2017-07-06 19:04:29
【问题描述】:

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

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

输出:

2017 年 6 月 29 日晚上 7:25

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

2017 年 6 月 29 日晚上 7:25 IST

Angular 提供了'z''Z' 的时区选项,但没有一个给出预期的结果:

'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

【问题讨论】:

  • 您能否详细说明“没有给出预期结果”?它是显示不正确的时区还是根本不显示?添加Z 似乎提供了plunkr 演示的正确时区。它以 3 个字符格式与我的时区完全匹配。
  • 已编辑问题。请检查。谢谢。
  • 我认为您需要编写自己的日期格式化管道来处理这个问题。它可以使用日期/时间格式的现有管道返回一个值,然后操纵时区以返回 3 位版本而不是全文。

标签: angular datetime date-pipe


【解决方案1】:

DatePipe 使用 Intl 来格式化日期。因此,由您的站点打开的系统决定应以何种格式返回当前时区。为了实现所需的行为,我建议您创建一个自定义 DatePipe,它将返回所需的 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

【讨论】:

  • 是的,这有帮助。谢谢你。让我们看看 Angular 团队是否会在即将发布的版本中更新为更短的时区格式..!!
  • 我认为这甚至不会被实现,因为它不依赖于 Angular,而是依赖于系统设置。根据您的浏览器和操作系统,它们可能会有所不同。因此,您可能会得到不同的结果。
  • 有什么办法可以使用夏令时
猜你喜欢
  • 1970-01-01
  • 2019-01-24
  • 2021-09-29
  • 1970-01-01
  • 2017-12-04
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多