1 回答

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。
添加回答
舉報