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

Martijn van den Bergh
  • 1,434
  • 1
  • 20
  • 40

4 Answers4

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 {}
  }
}
Robin Dijkhof
  • 18,665
  • 11
  • 65
  • 116
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.

steamfood
  • 474
  • 3
  • 10
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());
  });

}

ZAhmed
  • 1,232
  • 8
  • 15
-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.

Newerth
  • 449
  • 2
  • 12