Force Android DateUtils.getRelativeDateTimeString() to ignore the device locale?

独自空忆成欢 提交于 2019-12-04 00:27:41

According to the source code of the DateUtils class it uses both Resource.getSystem() and Locale.getDefault() method for formatting date and time. You can change the default Locale using Locale.setDefault() method but I don't think it's possible to change the return value of the Resource.getSystem() method. You can try to change the default locale to Locale.US but it seems to me that results will be even worse in this case.

This is working for me up to Android 7

  void forceLocale(Locale locale) {
    Configuration conf = getBaseContext().getResources().getConfiguration();
    updateConfiguration(conf, locale);
    getBaseContext().getResources().updateConfiguration(conf, getResources().getDisplayMetrics());

    Configuration systemConf = Resources.getSystem().getConfiguration();
    updateConfiguration(systemConf, locale);
    Resources.getSystem().updateConfiguration(conf, getResources().getDisplayMetrics());

    Locale.setDefault(locale);
  }

  void updateConfiguration(Configuration conf, Locale locale) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
      conf.setLocale(locale);
    }else {
      //noinspection deprecation
      conf.locale = locale;
    }
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!