Search code examples
javaspringspring-bootspring-mvcsimpledateformat

How to parse yyyymm data format to Month, YYYY format in Java?


I have a string value which is equal to "202004". how can I convert it to "April, 2020" in Java?


Solution

  • I would use java.time for a task like this.

    You can define two java.time.format.DateTimeFormatter instances (one for parsing the input string to java.time.YearMonth and another for formatting the obtained YearMonth to a string of the desired format).

    Define a method like this one:

    public static String convert(String monthInSomeYear, Locale locale) {
        // create something that is able to parse such input
        DateTimeFormatter inputParser = DateTimeFormatter.ofPattern("uuuuMM");
        // then use that formatter in order to create an object of year and month
        YearMonth yearMonth = YearMonth.parse(monthInSomeYear, inputParser);
        /*
         * the output format is different, so create another formatter
         * with a different pattern. Please note that you need a Locale
         * in order to define the language used for month names in the output.
         */
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(
                                                "MMMM, uuuu",
                                                Locale.ENGLISH
                                            );
        // then return the desired format
        return yearMonth.format(outputFormatter);
    }
    

    then use it, e.g. in a main method:

    public static void main(String[] args) {
        // your example input
        String monthInAYear = "202004";
        // use the method
        String sameMonthInAYear = convert(monthInAYear, Locale.ENGLISH);
        // and print the result
        System.out.println(sameMonthInAYear);
    }
    

    The output will be this:

    April, 2020