亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

確定用戶 Locale 是日-月-年還是月-日-年

確定用戶 Locale 是日-月-年還是月-日-年

小唯快跑啊 2023-04-19 16:21:12
與使用日-月-年的世界其他地區不同,美國使用月-日-年格式。我想以編程方式確定用戶是使用日-月還是月-日。我可以通過以下方式做到這一點,但我不確定是否有更簡單的方法?String localisedDateFormat = ((SimpleDateFormat) SimpleDateFormat.getDateInstance()).toPattern().toLowerCase(); boolean usFormat = localisedDateFormat.indexOf('d') > localisedDateFormat.indexOf('m');我不認為這對于 a 是可能的,DateTimeFormatter因為您無法獲得底層的pattern.
查看完整描述

1 回答

?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

TL;DR:調用此輔助方法,它返回YMD、DMY或MDY。


public static String getDateFieldOrder(Locale locale) {

? ? SimpleDateFormat fmt = ((SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale));

? ? return fmt.toPattern().replaceAll("[^yMd]|(?<=(.))\\1", "").toUpperCase();

}

要獲取字段順序,請請求一個DateFormat,并分析用于構建它的模式:


SimpleDateFormat fmt = ((SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale));

String pattern = fmt.toPattern();

這會給你這樣的模式:


dd.MM.yy

M/d/yy

y-MM-dd

d. M. y

因此,刪除非字母和重復字母:


pattern = pattern.replaceAll("\\P{L}", "").replaceAll("(.)\\1+", "$1");

要查看潛在結果,您可以運行此代碼 (Java 5+):


Map<String, Set<String>> map = new TreeMap<String, Set<String>>();

for (Locale locale : Locale.getAvailableLocales()) {

? ? SimpleDateFormat fmt = ((SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale));

? ? String pattern = fmt.toPattern().replaceAll("\\P{L}", "").replaceAll("(.)\\1+", "$1");

? ? Set<String> set = map.get(pattern);

? ? if (set == null)

? ? ? ? map.put(pattern, set = new TreeSet<String>());

? ? set.add(locale.getDisplayName(Locale.US));

}

for (Entry<String, Set<String>> entry : map.entrySet())

? ? System.out.println(entry.getKey() + " = " + entry.getValue());

樣本輸出(Java 11)


如果需要,您也可以刪除G和r模式字母。而不是replaceAll("\\P{L}", ""),使用replaceAll("[^yMd]", "")。


toUpperCase()如果您喜歡YMD,DMY和 之類的值,當然可以調用MDY。


查看完整回答
反對 回復 2023-04-19
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號