Fix Angular2 missing globalization capabilities till final release

I’ve started working with angular2 since a month. Due to my location in Switzerland, most projects language is german. Therefore dates, numbers and currencies have to be in the correct format. But Angular2 is still a release candidate. E. g. is it not possible to change the locale of the date pipe as we see can directly in the source on github.

Possible Solution

As possible working solution I decided to overwrite the date pipe globally. Here is how I achieved.

Own Date Pipe with Moment.js

I wrote the the following simple date pipe using Moment.js:

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

/*
    Format a date

    http://momentjs.com/docs/#/displaying/format/
*/

@Pipe({ name: 'date' })
export class DatePipe implements PipeTransform {
    transform(value: any, pattern: string = 'DD.MM.YYYY'): string {
        if (value === undefined || value === null) return null;

        let date = moment(value);
        return date.format(pattern);
    }
}

Then I globally registered the pipe in the bootstrap method like this:

import { AppComponent } from './app.component';
import { bootstrap }    from '@angular/platform-browser-dynamic';
import { PLATFORM_PIPES } from '@angular/core';

import { DatePipe } from "./shared/date.pipe";

bootstrap(AppComponent, [{ provide:PLATFORM_PIPES, useValue: [DatePipe], multi: true }]);

(Source: http://stackoverflow.com/a/38078961)

Now you can display a date like this where you want in the app:

<span>{{user.birthday | date}}</span>

Or you can display a date in a specific format (http://momentjs.com/docs/#/displaying/format/)

<span>{{user.birthday | date:'dddd, MMMM Do YYYY, h:mm:ss a'}}</span>

This would output: Sunday, February 14th 2010, 3:25:50 pm

Since en-US  is the default locale of Moment.js it had to be changed to de to solve my basic problem. This could be done before bootstraping the app:

import { AppComponent } from './app.component';
import { bootstrap } from '@angular/platform-browser-dynamic';
import { PLATFORM_PIPES } from '@angular/core';
import * as moment from 'moment';
import 'moment/../locale/de';

import { DatePipe } from "./shared/date.pipe";

moment.locale('de');

bootstrap(AppComponent, [{ provide:PLATFORM_PIPES, useValue: [DatePipe], multi: true }]);

(Further information and other options to set locale: http://momentjs.com/docs/#/use-it/typescript/)

This would no output: Donnerstag, Juli 21. 2016, 12:00:00 am

Other Pipes could be overwritten the same way.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top