Search code examples
angularjslocalizationdate-formattingangular-translate

Angular translate - format dates


I am using Angular translate for my app localization. I'd like to dynamically change the date format depending on the user's locale.

  • If the locale is French : format is dd/mm/yyyy
  • If the locale is English/US : format is mm/dd/yyyy
  • ...and so on depending on the locale's default date format

How can I achieve this (cleanly) with Angular translate ?


Solution

  • I finally ended using moment.js and Angular moment. Dates can be formatted to locale default with this:

    <td>{{user.lastLogin | amDateFormat:'l LT'}}</td>
    

    To change the moment locale, use the following:

    amMoment.changeLocale(language);
    

    Don't forget to import the moment locale files for the languages you wish to support:

    <script src="assets/global/plugins/moment.min.js"></script>
    <script src="jslib/angular-moment.min.js"></script>
    <script src="jslib/moment/de.js"></script>
    <script src="jslib/moment/es.js"></script>
    <script src="jslib/moment/fr.js"></script>
    <script src="jslib/moment/it.js"></script>
    <script src="jslib/moment/pl.js"></script>
    <script src="jslib/moment/ru.js"></script>
    <script src="jslib/moment/zh-cn.js"></script>
    

    And add angular moment module in your app:

    var myapp = angular.module('myapp', ['angularMoment']);