为了账号安全,请及时绑定邮箱和手机立即绑定

确定用户 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 关注
  • 68 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信