Angular 2 Datepipe formatting based on browser location/settings

大城市里の小女人 提交于 2020-01-04 04:08:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!