Angular 4: pipe date, UTC Local time: how to tell Angular the current time zone?

We use Angular 4 along with an MVC application written in the .net core. The data was obtained using the SignalR service, the hub is written in C #. The database contains a Datetime2 (7) (T-SQL) field, the resulting content looks like this (for a date field):

dueDt:"2017-10-02T08:54:00"

This is UTC time. We live in a +2 time zone. Now in the CSHTML file, we display this value as follows:

 <small>Due: {{item.dueDt | date:'dd.MM.yy HH:mm'}}</small>

which show something like: 09/27/17 12:43 PM which is good, the problem is that our time zone is not +0, but +2, so it should display 14:43 as time.

I read somewhere that Angulars DatePipe uses the local time zone of clients, but it doesn't seem to be happening. (I tried this with chrome, firefox and Edge - there is no difference). Does anyone have an idea why this is happening or how can I tell Angular what the local time zone is? I tried to enable angular -moment, but it really doesn't work. (I can detail this if it seems important, but this is another problem).

+4
source share
1 answer

I did something similar using moment.js, but Locale is really specific for each user configuration for locale and date template:

import { Injectable, Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
import { Observable } from 'rxjs/Rx';
import { UserService } from '../security/user/user.service';

@Pipe({
    name: 'formatDate'
})
@Injectable()
export class DateTimePipe implements PipeTransform {

    constructor(private userService: UserService) {

    }

    /**
     * Asynchronous pipe, transforms a date into a formatted date.
     * The transformation is based on the 'locale' and 'pattern' properties from the current user preferences.
     * Usage: this pipe need to be followed by the'async' pipe, since it returns an Observable.
     */
    transform(value: any, showTime?: boolean): Observable<string> {
        if (value) {
            return this.userService.getPreferences()
                .map(prefs => {
                    const locale = prefs.preferences.get('locale');

                    let pattern;
                    if (showTime) {
                        pattern = prefs.preferences.get('dateTimeFormat') || 'DD/MM/YYYY HH:mm';
                    } else {
                        pattern = prefs.preferences.get('dateFormat') || 'DD/MM/YYYY';
                    }

                    moment.locale(locale);

                    let date = value instanceof Date ? value : new Date(value);
                    return moment(date).format(pattern);
                });
        }
        return Observable.of(value);
    }
}

you can also change local with moment

moment.locale('en_GB')

See here https://momentjs.com/ for more details.

+3

Source: https://habr.com/ru/post/1686646/


All Articles