java – 如何知道Locale是使用12或24小时格式?

前端之家收集整理的这篇文章主要介绍了java – 如何知道Locale是使用12或24小时格式?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > How do I find out whether a locale uses 12 or 24 hour time in Java?3个
我想知道,从Locale,我是否必须使用24或12格式.

我找到了这个:

  1. if (android.text.format.DateFormat.is24HourFormat(getApplicationContext()))

但是这会根据系统返回一个布尔值,而不是Locale.这意味着如果用户使用英语为应用程序但使用24小时格式的手机,它将返回true …

我怎样才能得到一个布尔值告诉我使用的格式是否是24小时?我不是在使用Joda.提前致谢.

编辑似乎有些人认为这是重复的,我已经阅读了你提供的帖子作为重复标志的来源.它只能通过近似的变通方法或提供日期的方法解决,大部分时间都是当前的,即使它是相应的格式.

你可以猜到,如果我想要一种方法来知道我是否应该根据Locale使用12小时格式,这意味着我不需要日期或任何东西,我已经拥有,但是确认我必须使用的格式.

解决方法

看一下实际的android.text.format.DateFormat.is24HourFormat方法source code,您将看到它们是如何做到的:
  1. Locale locale = context.getResources().getConfiguration().locale;
  2.  
  3. java.text.DateFormat natural =
  4. java.text.DateFormat.getTimeInstance(
  5. java.text.DateFormat.LONG,locale);
  6.  
  7. if (natural instanceof SimpleDateFormat) {
  8. SimpleDateFormat sdf = (SimpleDateFormat) natural;
  9. String pattern = sdf.toPattern();
  10. if (pattern.indexOf('H') >= 0) {
  11. value = "24";
  12. } else {
  13. value = "12";
  14. }
  15. } else {
  16. value = "12";
  17. }

因此,您可以根据您获取区域设置的方式进行调整.

猜你在找的Java相关文章