Home > other >  How to format datetime based on timezone dynamically
How to format datetime based on timezone dynamically

Time:02-26

I have tried different ways to format, but couldn't get what I want. In my angualr App, I have data from database, like this

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

With Kendo format, I was able to convert the time to local time based on the time zone, the result is: Wed Feb 16 2022 17:00:00 GMT-0500 (EST), but when I applied date pipe, it always convert back to old time. I tried is date: 'dd/MM/yyyy hh:mm a' since I need it to be '02/16/2022, 05:00 PM'. I tried other format as well, but none was working. Please tell me which part went wrong, time format, or time zone convert? Below is the code to convert with Kendo. In ts:

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

in html:

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

Thanks in advance

CodePudding user response:

Angular date pipe uses local time zone if not provided.

You can use Angular common formatDate function in your convertTest like this

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

Or You can use timezone in date pipe like this

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

CodePudding user response:

finally, I figured out. I posted it for anyone if having same issue. I also need to import kendo package. import '@progress/kendo-date-math/tz/all'; import { IntlService } from "@progress/kendo-angular-intl"

then will get result from const from: Date = ZonedDate.fromLocalDate(new Date(dateTime), zone);
return this.intl.formatDate(from, "dd/MM/yyyy hh:mm a")

  • Related