0

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?

Pavel Poley
  • 5,307
  • 4
  • 35
  • 66

1 Answers1

1

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.

SRIDHARAN
  • 1,196
  • 1
  • 15
  • 35
  • It may help, thanks, btw for what used one letter in `SimpleDateFormat`(d/M/y)? – Pavel Poley May 05 '20 at 15:52
  • https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html Here is the expansion for each letter. May be I'm not getting your question ? Can you please elaborate a bit ? – SRIDHARAN May 05 '20 at 16:21
  • I mean for example, why `d` and `dd` show same result = `22` – Pavel Poley May 05 '20 at 16:35
  • The different is in single digit. Example: d/MM/yyyy for 5/06/1997. dd/MM/yyyy => 05/06/1997 – SRIDHARAN May 05 '20 at 17:03
  • 1
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `DateFormat` and `SimpleDateFormat` classes. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. May 05 '20 at 18:15
  • Sure. Understand your point. It was not me suggesting simpledateformat. It was in the question and I just extended on it. – SRIDHARAN May 05 '20 at 18:17
  • Sorry, I didn’t see the first versions of the question, or I would instead have posted a comment under the question warning against the old and troublesome classes. The references to `DateFormat` and `SimplDateFormat` have later been deleted from the question. – Ole V.V. May 06 '20 at 17:07