DateFormat month to uppercase

10,003

Solution 1

SimpleDateFormat cannot give you that (though you just might consider if you can develop a subclass that can). But java.time, the modern Java date and time API, can:

    Map<Long, String> monthNames = Arrays.stream(Month.values())
            .collect(Collectors.toMap(m -> Long.valueOf(m.getValue()), Month::toString));
    DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
            .appendText(ChronoField.MONTH_OF_YEAR, monthNames)
            .appendPattern(" d, uuuu")
            .toFormatter();
    LocalDate date = LocalDate.of(2018, Month.OCTOBER, 21);
    String formattedDate = date.format(dateFormatter);
    System.out.println(formattedDate);

Output from this snippet is what you requested:

OCTOBER 21, 2018

I have assumed you need this in English only. For other languages you would just have to populate the map differently.

This is just as well because you shouldn’t want to use SimpleDateFormat anyway. That class is not only long outdated, it is also renowned for being troublesome. java.time is generally so much nicer to work with.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Solution 2

You can do something like this:

SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
String dateStr = sdf.format(new Date());
System.out.println( dateStr.toUpperCase() );

Brief Description:

first we create an instance of SimpleDateFormat and pass as parameter the default "MMMM dd, yyyy" which will result in "Month day, year".

Then we pass the current date (new Date () or your date) to the class SimpleDateFormat to do the conversion.

Finally, we use toUpperCase() so that the text is uppercase.

I hope I've helped! :D

Share:
10,003

Related videos on Youtube

Serhii Kovalenko
Author by

Serhii Kovalenko

Updated on June 04, 2022

Comments

  • Serhii Kovalenko
    Serhii Kovalenko almost 2 years

    How to format the date to the following view OCTOBER 21, 2018 (the month in upper case)? I can get it by "%1$TB %1$te, %1$tY" pattern, but I need to do it by SimpleDateFormat. Can you suggest me how I can do it?

  • kumesana
    kumesana almost 6 years
    I have a weird insecurity with toUpperCase() and toLowerCase(). If for some reason your code ever runs in April on a computer set on Turkish as default language, you'll get: APRİL 21, 2018. Notice the dot on the capital I. I always call them like dateStr.toUpperCase(Locale.ROOT)