bensiu
bensiu

Reputation: 25604

Angular 4 - DateFormatter - how to

I have application in Angular 2 that use custom formatting date to Polish:

return DateFormatter.format( new Date( date + ' 12:00:00' ), 'pl-PL', 'd MMMM y' );

It is possible by importing class

import { DateFormatter } from '@angular/common/src/facade/intl';

Next, I converting/upgrading my application to Angular 4.3 and this class (DateFormatter) is no longer there.

I someone knows where it is located, or what other methods I should use to achieve such formatting?

Upvotes: 0

Views: 2266

Answers (2)

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19764

The DateFormatter class can currently be found here in source code.

However, Angular disallows importing from deep path such as this one. If @angular/common does not expose the function you're looking for, it means it's private and you're not supposed to be using it (which is why your application broke after upgrading).

Consider using the DatePipe or a utility library such as date-fns.

Upvotes: 1

Eduard Lepner
Eduard Lepner

Reputation: 699

In our application we use date pipe. E.g. <p class="dIB">{{bfPreventer.nextControlDate | date: 'shortDate'}}</p>

By default it takes the current culture of your browser. But you can change it at start up. I'm not sure if it's perfect, but it works for us well.

@NgModule({
bootstrap: [AppComponent],
declarations: [
    ...pageComponents
],
imports: [
    BrowserModule,
    ...
    TranslateModule.forRoot(),

],
providers: [

    { provide: LOCALE_ID, useValue: window.navigator.language.indexOf("en") >= 0 ? "en-US" : "nb-NO" },

]})

Also, please take into the consideration that the pipe relies on i18n API of the browser, so old browsers might have issues with that.

Upvotes: 0

Related Questions