Home > database >  Angular Date convert from UTC to local time
Angular Date convert from UTC to local time

Time:06-27

I have a question regarding Date in Angular. From backend I'm getting the date and time as UTC. What i need is in frontend i want to display the UTC date(coming from backend) in the local timezone of the respective country.

How can I achieve that?

CodePudding user response:

You can either use the date pipe per @JSON Derulo's comment, or make use of Luxon (Moment's successor).

E.g.

import { DateTime } from 'luxon';

export class DateHelper {

    public static fromIsoString(str: string): Date {
        return DateTime.fromISO(str, {zone: 'utc'}).toJSDate();
    }

}

And usage:

public onServerResponse(someDateString: string): void {
    const date = DateHelper.fromIsoString(someDateString);
    // do whatever you want with your shiny new JS Date object...
    console.log('local date: ', date);
}

... assuming that you are formatting your dates coming from the backend as ISO strings (I recommend doing so).

CodePudding user response:

You could use Date pipes for this. This automatically converts UTC to local time.

<span>{{ yourDate| date: 'medium' }} </span>

For more information, refer to this documentation.

  • Related