如何根据时区动态格式化日期时间

How to format datetime based on timezone dynamically

我尝试了不同的格式化方式,但无法得到我想要的。 在我的 angualr 应用程序中,我有来自数据库的数据,像这样

PacificTime TimeZoneCode    TimeZone
2022-02-16 14:00:00.000 US/Eastern  ET

使用 Kendo 格式,我能够根据时区将时间转换为本地时间,结果是:Wed Feb 16 2022 17:00:00 GMT-0500 (EST),但是当我应用日期管道时,它总是转换回旧时间。我试过日期:'dd/MM/yyyy hh:mm a' 因为我需要它是 '02/16/2022, 05:00 PM'。我也尝试了其他格式,但 none 有效。请告诉我哪里出错了,时间格式,还是时区转换?下面是用 Kendo 转换的代码。 在 ts:

    convertTest(dateTime: string, zone: string) {
    const from = new Date(dateTime);
    const to = ZonedDate.fromLocalDate(from, zone)    
    return to
  }

在html中:

{{convertTimezone(dataItem.pacificTime, dataItem.imeZoneCode    ) | date: 'dd/MM/yyyy hh:mm a' }}

提前致谢

Angular 如果未提供,则日期管道使用本地时区。

您可以像这样在 convertTest 中使用 Angular 通用格式日期函数

convertTest(dateTime: string, zone: string) {
  return formatDate(dateTime, "dd/MM/yyyy hh:mm a", "en-US", zone);
}

或者您可以像这样在日期管道中使用时区

{{dataItem.pacificTime | date: 'dd/MM/yyyy hh:mm a' : dataItem.imeZoneCode }}

终于,我想通了。如果有同样的问题,我将它发布给任何人。 我还需要导入 kendo 包。 导入“@progress/kendo-date-math/tz/all”; 从“@progress/kendo-angular-intl”

导入 { IntlService }

然后将从 const 来自:Date = ZonedDate.fromLocalDate(new Date(dateTime), zone);
return this.intl.formatDate(来自, "dd/MM/yyyy hh:mm a")