Search code examples
javaandroiddatesimpledateformat

How to customize date format of SimpleDateFormat() in Java (android)?


In my PHP webpage, I used this code (given below), which gives me the day's date in my desired format, which is (example) 2nd Oct. 2021.

<?php
date_default_timezone_set('Asia/Calcutta');
echo date('jS M\. Y'); //result = 2nd Oct. 2021
?>

Now, I want to achieve the same with Java - when I tried adding the format jS M\. Y in Java (android), it showed me some errors I'm unable to understand... Here's what I've tried in Java -

String date = new SimpleDateFormat("jS M\. Y", Locale.getDefault()).format(new Date());

I am currently new to Java & just found out about this class, so I don't know a lot of things 😪 What should I do in order to get the day's date in my desired format? Please guide me... Thanks!


Solution

  • java.time

    The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

    Solution using java.time, the modern Date-Time API:

    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeFormatterBuilder;
    import java.time.temporal.ChronoField;
    import java.util.HashMap;
    import java.util.Locale;
    import java.util.Map;
    
    public class Main {
        public static void main(String[] args) {
            LocalDate date = LocalDate.now(ZoneId.of("Asia/Kolkata"));
            DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                                    .appendText(ChronoField.DAY_OF_MONTH, ordinalMap())
                                    .appendPattern(" MMM. uuuu")
                                    .toFormatter(Locale.ENGLISH);
            String output = date.format(dtf);
            System.out.println(output);
        }
    
        static Map<Long, String> ordinalMap() {
            String[] suffix = { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
            Map<Long, String> map = new HashMap<>();
    
            for (int i = 1; i <= 31; i++)
                map.put((long) i, String.valueOf(i) + suffix[(i > 3 && i < 21) ? 0 : (i % 10)]);
    
            return map;
        }
    }
    

    Output:

    2nd Oct. 2021
    

    ONLINE DEMO

    Learn more about the modern Date-Time API from Trail: Date Time.


    Update

    A valuable comment from Joachim Sauer:

    Since this is tagged as Android, it should be noted that java.time is available in Android since 8.0 (Oreo) and most of it can be accessed even when targeting older versions through desugaring.


    * For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.