2016-07-23 88 views
3

如何指定dateFormat元素并尊重当前区域设置规则?我知道我可以使用SimpleDateFormat并指定我喜欢的格式 - 但它可能在不同的国家/地区是错误的。关于当前区域设置的自定义Android日期格式化

我试图掩盖DateFormat的元素,但它仅接受短期,中期和LONG:

DateFormat dayMonth = DateFormat.getDateInstance(DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD | DateFormat.MONTH_FIELD); 

Caused by: java.lang.IllegalArgumentException: Illegal date style: 11 
at java.text.DateFormat.checkDateStyle(DateFormat.java:843) 
at java.text.DateFormat.getDateInstance(DateFormat.java:378) 

我想获得“2016年10月”,或“RIJ 2016”。这可以实现:

DateFormat dayMonth = new SimpleDateFormat("MMM yyyy"); 

但我不想在我的应用程序中硬编码此格式。我只看到一种方式:把它放到strings.xml中,翻译者必须设置它。或者有更好的方法吗?

+0

你有没有看着'LocalDateTime' - 也许这可能是SOM你在找什么?一个例子是:'LocalDateTime.parse(“2016-07-22”)' – ishmaelMakitla

+0

有趣的类,但它的格式方法需要DateTimeFormatter作为参数 - 我们回到我的问题。 –

+0

我明白了,DateTimeFormatter.ISO_LOCAL_DATE_TIME是什么呢,它的'format'方法需要'TemporalAccessor' - 可以是'LocalDateTime.parse(“2016-07-22”)'。 – ishmaelMakitla

回答

2

Android有DateFormat.getBestDateTimePattern()实现这一

pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), "MMMyyyy"); 
dayMonth = new SimpleDateFormat(pattern); 

唯一的缺点是18 API级别我亲自使用的DateFormat.getMediumDateFormat()作为后备的结果。或者,您可以忽略旧设备的区域设置,并使用new SimpleDateFormat("MMM yyyy")作为回退或尝试回溯这一方法。

OP编辑

我试图在Nexus 5X与Android 6下面的代码

for (Locale locale : locales) { 
    format = android.text.format.DateFormat.getBestDateTimePattern(locale, "MMMyyyy"); 
    DateFormat dateFormat = new SimpleDateFormat(format, locale); 
    log.debug("{}: {}", locale.getCountry(), dateFormat.format(new Date())); 
} 

这里有一些结果:

  • NA:2016年7月
  • AE :يوليو2016
  • BG:07.2016г.
  • CZ:červenec2016
  • FR:Goue 2016
  • DE:巨力2016
  • GB:2016年7月
  • FI:heinä2016
  • IT:吕2016
  • HR:SRP 2016年
  • RU:июль2016
+0

感谢您的提示。我已经用我的发现更新了你的答案。结果对一些国家不利。 –