Angular 2 date formatting based on location / browser settings

Is there a way to make the dumping dynamics so that if it is an American browser, the datapika will return the American format (yyyy / MM / dd), and when it is in the European browser, it will return the European format (dd / MM / yyyy)

thank

+3
source share
4 answers

This can be tricky, especially when using aot. It usually takes you to make different builds. I expanded the datapipe and used the browser language.

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 {}
  }
}
+4
source

You can check the location and put it in the if statement Yes, you can use a pipe like this:

     <div *ngif="Location() === 'Europe' "
     {{valueDate | date: 'dd/MM/yyyy'}}
     <div>
     <div *ngif="Location() === 'Ammerica' "
     {{valueDate | date: 'MM/dd/yyyy'}}
     <div>

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

}

+1

I think you should use the native JS API Date.prototype.toLocaleDateString()to achieve this. See this link .

You can implement your own Angular pipe to use this API.

+1
source

I know this may seem annoying, but it's a lot easier than asking Angular to do this 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, do it pipe.

0
source

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


All Articles