Reputation: 2171
Unlike newer versions of Angular, Angular 4 DatePipe doesn't seem to support passing in a timezone as a parameter.
I have a backend service returning an ISO 8601 formatted datetime string without timezone (e.g., 2018-12-04T19:01:50.062
) -- stored and returned as UTC.
Using DatePipe
, how can I show the datetime as the user's local time?
Upvotes: 5
Views: 13344
Reputation: 2171
Angular 4's DatePipe
supports the UTC zone designator suffix ('Z'), so if the value you pass to the pipe is a UTC datetime, then your backend service can return your datetime with the 'Z' zone designator or you can append Z
and it will show the date time in the user's local time.
For example,
<span class="date">{{ value + 'Z' | date:'short' }}</span>
NOTE: You need to make sure you are providing Angular's LOCALE_ID dynamically to the correct locale (import the exported provider into your app module), if you want DatePipe
to use the user's browser settings:
export class WindowRefService {
public getWindow(): Window {
return window;
}
}
export function languageFactory(windowRef: WindowRefService): string {
return windowRef.getWindow().navigator.language;
}
export const localeProvider = {
provide: LOCALE_ID,
deps: [WindowRefService],
useFactory: languageFactory
};
See other questions on LOCALE_ID
: Angular4: Locale for a user
Upvotes: 22