android - 强制 Android DateUtils.getRelativeDateTimeString() 忽略设备区域设置?

标签 android date time locale relative-date

我发现使用返回“昨天”或“2 小时前”等值的 android.text.format.DateUtils 相关 API 非常好 - 但我的应用程序不支持所有 Android 语言做。因此,我默认使用英语,但对于我不支持的每种语言,相关字符串都会显示在设备设置中。

例如,喜欢:

上次尝试:11 分钟。

对于我不支持的任何语言,我想让 API 调用默认为英语。但是,我看不到任何地方可以为 API 调用设置区域设置 - 我希望我只是在某处遗漏了它。

有没有办法只为 API 调用设置区域设置,而忽略设备设置?

最佳答案

这适用于 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;
    }
  }

关于android - 强制 Android DateUtils.getRelativeDateTimeString() 忽略设备区域设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6539195/

相关文章:

android - 带有模糊层的谷歌地图

android - com.android.dx.util.DexException : Multiple dex files define

Javascript:计算给定年份的月份天数

c# - 将文本格式化为日期/时间格式 c#

java - 如何将 jodatime 持续时间转换为格式为 hh :mm:ss? 的字符串

android - kotlin中方法时间的功能是什么?

android - 在 Xamarin 中隐藏 Android 标题栏有延迟

java - 将纪元时间转换为人类格式日期和时间时输出错误?

mysql sql查询以避免日期总和中的周末

python - 如何让 Python 函数休眠一段时间,而游戏的其余部分继续进行?