【问题标题】:Ember-moment how to format the date/time according to localeEmber-moment 如何根据语言环境格式化日期/时间
【发布时间】:2018-09-05 13:36:00
【问题描述】:

我坚持使用浏览器区域设置使用ember-moment 插件来格式化日期/时间。我在 environment.js 中定义了包含的语言环境,如他们的自述文件中所述:

moment: {
  includeLocales: true
}

然后在手把模板中我尝试显示日期:

{{moment-format urrentShop.shop.openingDate 'L'}}

但日期仍以美国格式显示:

03/27/2018

而不是法国的。关于如何解决这个问题的任何想法?

【问题讨论】:

  • 也许this的问题可以帮助你。

标签: ember.js momentjs


【解决方案1】:

我正在使用 ember-i18n 插件。我按照他们的文档中的描述设置了语言环境检测:

#app/instance-intializers/i18n.js

export function initialize(applicationInstance) {
  let i18n = applicationInstance.lookup('service:i18n');
  let moment = applicationInstance.lookup('service:moment');
  let locale = calculateLocale(i18n.get('locales'));
  i18n.set('locale', locale);  
  moment.setLocale(locale);
}

function calculateLocale(locales) {
  // whatever you do to pick a locale for the user:
  const language = navigator.languages[0] || navigator.language || navigator.userLanguage;

  return  locales.includes(language.toLowerCase()) ? language : 'en-GB';
}

export default {
  name: 'i18n',
  initialize
};

如你所见,我必须补充:

let moment = applicationInstance.lookup('service:moment');
moment.setLocale(locale);

moment 服务上设置区域设置。 我也加了environment.js

moment: {
  includeLocales: true
}

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    ember-moment 默认为语言环境en。您可以在运行时使用this.get('moment').setLocale('fr'); 更改它(请参阅ember-moment/readme):

    // app/routes/applicaton.js
    export default Ember.Route.extend({
      moment: Ember.inject.service(),
      beforeModel() {
        this.get('moment').setLocale('fr');
      }
    });
    

    使用浏览器区域设置:

    // app/routes/applicaton.js
    export default Ember.Route.extend({
      moment: Ember.inject.service(),
      beforeModel() {
        let locale = window.navigator.userLanguage || window.navigator.language; // e.g. fr-FR
        if (locale) {
          this.get('moment').setLocale(locale.substr(0,2));
        }
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多