通用日期格式掩码,用于手动输入日期

huangapple go评论61阅读模式
英文:

Universal date format mask for manual date input

问题

在Android中是否有一种方法根据区域设置动态输入和格式化EditText的日期?意图是基于区域设置创建手动日期输入的EditText

有各种不同的模式,例如:

2021-10-22    y-MM-dd        -    ce_RU
22.10.21      dd.MM.yy       -    de_LI
22/10/2021    dd/MM/y        -    en_001
21. 10. 22.   yy. M. d.      -    ko_KP
[10/22/21]    [M/d/yy]       -    en_XA
2021/10/22    y/M/d          -    zh_CN_#Hans
22.10.21 г.   d.MM.yy 'г'.   -    bg_BG

我们可以为所有区域设置显示格式化的日期文本,但不能根据区域设置手动输入预格式化的日期文本?

英文:

Is there way in Android to dynamically enter and format date for EditText based on locale?The intent is to create manual date input EditText locale based.

There are various of patterns for example:

2021-10-22    y-MM-dd        -    ce_RU
22.10.21      dd.MM.yy       -    de_LI
22/10/2021    dd/MM/y        -    en_001
21. 10. 22.   yy. M. d.      -    ko_KP
[10/22/21]    [M/d/yy]       -    en_XA
2021/10/22    y/M/d          -    zh_CN_#Hans
22.10.21 г.   d.MM.yy 'г'.   -    bg_BG

We can show formatted date text for all locales but cannot manually enter pre-formatted text date based on locale?

答案1

得分: 1

根据我所知,DateFormat 中没有将 M 转换为 MM 或 d 转换为 dd 的功能。您可以通过编写 if else 语句块来实现此功能。

无论如何,由于您已经在字符串中具有模式,您可以在解析之前使用正则表达式将其转换为所需的格式。

Format dateFormat = android.text.format.DateFormat.getDateFormat(getContext());
String pattern = ((SimpleDateFormat) dateFormat).toLocalizedPattern();
pattern = pattern.replaceAll("(?i)(M)+","M").replaceAll("M", "MM");
pattern = pattern.replaceAll("(?i)(y)+","y").replaceAll("y", "yyyy");
pattern = pattern.replaceAll("(?i)(d)+","d").replaceAll("d", "dd");

希望这有所帮助。

英文:

As far as I know, None of the DateFormat does the conversion of M to MM or d to dd. You can do it by writing if else blocks.

Anyway, Since you already have the pattern in string, you can convert it to desired format using regex before doing the parsing.

Format dateFormat = android.text.format.DateFormat.getDateFormat(getContext());
String pattern = ((SimpleDateFormat) dateFormat).toLocalizedPattern();
pattern = pattern.replaceAll("(?i)(M)+","M").replaceAll("M", "MM");
pattern = pattern.replaceAll("(?i)(y)+","y").replaceAll("y", "yyyy");
pattern = pattern.replaceAll("(?i)(d)+","d").replaceAll("d", "dd");

Hope this helps.

huangapple
  • 本文由 发表于 2020年5月5日 20:14:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/61612901.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定