2016-07-23 49 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

感謝您的提示。我已經用我的發現更新了你的答案。結果對一些國家不利。 –

相關問題