Angular 2 Datepipe formatting based on browser loc

2019-07-07 06:13发布

问题:

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:

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());
  });

}



回答3:

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.