1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Issue with Timezone Conversion in Angular Date Function

Discussão em 'Angular' iniciado por Jobz, Junho 25, 2025.

  1. Jobz

    Jobz Guest

    I'm working on an Angular project where I frequently use the JavaScript

    new Date()


    function. We have a new requirement to change the timezone of every date to match the timezone specified in the user's account profile, regardless of the user's location. To achieve this, I created a reusable function that adjusts the timezone of a date. Below is the implementation:

    newTimezoneDate(dateVal?: any): Date {
    let timeZone: string | null = this.configService.getFacilityTimeZone();
    if (!timeZone) {
    timeZone = localStorage.getItem(facilityTimezone);
    }
    let date = new Date();
    if (dateVal) {
    date = new Date(dateVal);
    }
    if (!timeZone) {
    return date; // Return the date object if no timezone is provided
    }
    // Convert the date to the specified timezone
    const formattedDate = this.formatDateToTimeZone(date, timeZone);

    return formattedDate; // Return the converted date
    }

    formatDateToTimeZone(date: Date, timeZone: string) {
    try {
    return new Date(date.toLocaleString('en-US', { timeZone }));
    } catch (error) {
    // If an error occurs, use the default user's timezone
    return date;
    }
    }


    Problem The function works as expected, but I'm facing an issue when I pass a date that has already been created using this function. In such cases, I receive incorrect date values.

    Question How can I modify the newTimezoneDate() function to correctly handle dates that have already been converted to the specified timezone? Is there a way to check if the date being passed is already in the correct timezone, so I can avoid unnecessary conversions?

    Any help or suggestions would be greatly appreciated!

    Continue reading...

Compartilhe esta Página