How to display month in text in java?

Question:

I have the following and it paints the month but in number, and I want to show it in text (January, February, etc.). How can I show it in text?

private int annio;
private int mes;
Calendar c1 = Calendar.getInstance();
public void obtenerMesAño() {
   annio = c1.get(Calendar.YEAR);
    mes = c1.get(Calendar.MONTH)+1;

}

Answer:

If you use Java 8 you can use the package time classes to get the name of the month. It is very simple, you only need two lines.

// Obtienes el mes actual
Month mes = LocalDate.now().getMonth();

// Obtienes el nombre del mes
String nombre = mes.getDisplayName(TextStyle.FULL, new Locale("es", "ES"));

The only detail is that the name of the month is given in lowercase, but that's not much of a problem, with the following block of code you easily convert the first letter of the month into uppercase.

// Convierte a mayúscula la primera letra del nombre.
String primeraLetra = nombre.substring(0,1);
String mayuscula = primeraLetra.toUpperCase();
String demasLetras = nombre.substring(1, nombre.length());
nombre = mayuscula + demasLetras;

System.out.println(nombre);

Remember to import the necessary libraries.

import java.time.LocalDate;
import java.time.Month;
import java.time.format.TextStyle;
import java.util.Locale;
Scroll to Top