Angular 2 Datepipe formatting based on browser location/settings
Asked Answered
N

4

6

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

Noah answered 8/8, 2017 at 7:10 Comment(0)
G
4

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 {}
  }
}
Gizela answered 8/8, 2017 at 7:26 Comment(4)
Sorry for my ignorance but what do you mean exactly with window? is that just a window.ts file? How do i implement this in my Angular project?Noah
It is a simple serviceGizela
What is isNullOrUndefined ? My editor doesn't recognize it.Noah
import {isNullOrUndefined} from 'util';Gizela
C
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.

Catalase answered 14/6, 2018 at 4:11 Comment(0)
F
0

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

}

Fallen answered 8/8, 2017 at 7:13 Comment(3)
Could you please explain how i can check the location? Dont i need permission from the user to do that?Noah
I edit the code above , see the code , I hope it is usefulFallen
Thanks for the answer, i think this will also work indeed. But i do think the answer from Robin Dijkhof is a little better because it looks for the language in the browser settings. Nevertheless this will also work, so thanks!Noah
I
-1

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.

Iphigenia answered 14/10, 2019 at 10:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.