问题
Is there a way to make the datepipe dynamic so that if it's an American browser the datepipe returns the American format (yyyy/MM/dd) and when it's a European browser it returns the European format (dd/MM/yyyy)?
Thanks
回答1:
This can be hard, especially when using aot. It would normally require you to make different builds. I extended the datapipe and use the browsers locale.
Datepipe:
@Pipe({name: 'datepipe', pure: true})
export class MyDatePipe extends DatePipe implements PipeTransform {
constructor(private win: WindowRef) {
super(win.ln);
}
transform(value: any, pattern?: string): string | null {
return super.transform(value, pattern);
}
}
Window:
function _window(): any {
// return the global native browser window object
return window;
}
@Injectable()
export class WindowRef {
get nativeWindow(): any {
return _window();
}
public ln = 'en';
constructor() {
try {
if (!isNullOrUndefined(this.nativeWindow.navigator.language) && this.nativeWindow.navigator.language !== '') {
this.ln = this.nativeWindow.navigator.language;
}
}finally {}
}
}
回答2:
I think you should use native JS API Date.prototype.toLocaleDateString()
to achieve this goal. See this link.
You can implement your own Angular pipe to use this API.
回答3:
You can check the location and put it in if statement Yes you can use pipe like this :
<div *ngif="Location() === 'Europe' "
{{valueDate | date: 'dd/MM/yyyy'}}
<div>
<div *ngif="Location() === 'Ammerica' "
{{valueDate | date: 'MM/dd/yyyy'}}
<div>
To find location
getCurrentLocation(lat,lng): Observable<any> {
return this._http.get("http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true")
.map(response => response.json())
.catch(error => {
console.log(error);
return Observable.throw(error.json());
});
}
回答4:
I know that this may seem nasty but it's way simpler than begging Angular to do it for you:
public renderLocaleDateTime(date: Date, dateStyle = 'medium', timeStyle = 'medium'): string {
var script = 'const date = new Date("' + date + '"); const options = { dateStyle: "' + dateStyle + '", timeStyle: "' + timeStyle + '" }; date.toLocaleString({}, options);';
return eval(script);
}
And then:
<span title="{{ renderLocaleDateTime(date, 'long', 'long') }}">
{{ renderLocaleDateTime(date) }}
</span>
Or even better, make it a pipe.
来源:https://stackoverflow.com/questions/45561546/angular-2-datepipe-formatting-based-on-browser-location-settings