Java Android Calendar/DateFormat this format XXXXXXXX [closed]

Here’s the modern answer and some additional thoughts.

For most purposes you should not want your date formatted to 27032019. It’s not easily readable by humans and not recommended for serialization.

Also consider not using Calendar, DateFormat, SimpleDateFormat or Date. Those classes are long outdated and poorly designed. Instead you may use java.time, the modern Java date and time API. It’s so much nicer to work with.

Serialization using java.time and ThreeTenABP

If you need your date string to be machine readable — for example if it’s for a JSON or for storing into a text file from where you or someone else needs to read it back — use the standard ISO 8601 format. LocalDate.toString produces this format, so we don’t need any explicit formatter:

    final String currentDate
            = LocalDate.now(ZoneId.of("Africa/Khartoum")).toString();
    System.out.println(currentDate);

Output when running today is:

2019-03-27

A compacter ISO 8601 format

If you insist on a compact format without any punctuation, ISO 8601 offers that too:

    final String currentDate = LocalDate.now(ZoneId.of("Africa/Khartoum"))
            .format(DateTimeFormatter.BASIC_ISO_DATE);

20190327

Your format

And if you really insist (I don’t see why you should), java.time can of course produce your requested format too:

    final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("ddMMuuuu");
    final String currentDate = LocalDate.now(ZoneId.of("Africa/Khartoum"))
            .format(dateFormatter);

27032019

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages. My imports for the above snippets are:

    import org.threeten.bp.LocalDate;
    import org.threeten.bp.ZoneId;
    import org.threeten.bp.format.DateTimeFormatter;
    

Links

Leave a Comment