joanllenas / ngx-date-fns

⏳ date-fns pipes for Angular
164 stars 14 forks source link

What is the amLocal equivalent of ngx-moment? #367

Closed GitHubish closed 2 years ago

GitHubish commented 2 years ago

I am trying to migrate ngx-moment to ngx-date-fns since momentjs is no longer maintained. Only I understand that it is not quite possible to do the same thing. In my case all dates are stored in UTC in the database. The "format" of the dates returned by the backend is in ISO (C# ASP Core). So to date I was doing this for example with ngx-moment:

{{ myDate | amFromUtc | amLocal | amDateFormat:'LL' }}

I understand that the equivalent of amFromUTC is dfnsParseIso in ngx-date-fns

But what about amLocal how to do it? I see that you should use date-fns-tz but ngx-date-fns doesn't offer a pipe to use it. So I created something like that, but it doesn't work, the date displayed is still not according to the user's timezone.

import { Pipe, PipeTransform } from '@angular/core';

import { zonedTimeToUtc, utcToZonedTime, format } from 'date-fns-tz';

@Pipe({ name: 'utcToZonedTime' })
export class UtcToZonedTimePipe implements PipeTransform {
  transform(
    dateString: string
  ): string {
    const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    return utcToZonedTime(dateString, timezone);
  }
}

Have you got an idea? Why not integrate the pipe to use date-fns-tz? Thanks

joanllenas commented 2 years ago

I'm not familiar with momentjs.

Anyway, if the browser gets a UTC date such '2021-10-15T09:00:00.000Z' and you are in Spain (currently GMT+2) and you format it with yyyy-MM-dd HH:mm:ss you get the proper local time 2021-10-15 11:00:00.

// component
serverDate = '2021-10-15T09:00:00.000Z';
localDate = new Date(this.serverDate);
// template
<p>{{ localDate | dfnsFormat: 'yyyy-MM-dd HH:mm:ss' }}</p>
// result
2021-10-15 11:00:00

Is that what you need?

joanllenas commented 2 years ago

Feel free to reopen if you need more help.