I want to extract the month from a full date (DD/MM/YYYY)
. I have found a way to do it:
int mes = cal.get(Calendar.MONTH);
String nombreMes = mes.getDisplayName(TextStyle.FULL, new Locale("es",
"ES"));
But it gives me problems with the TextStyle of java.time : it doesn't pick up the import
.
Should we add any dependencies in the pom.xml to be able to work with the java.time elements ? If so, can you provide me with the dependency to add in the pom.xml ?
From what I can see, your first error should be the name of the variable
mes
, because the variableint mes
must not have the methodgetDisplayName
that would belong to the variableCalendar cal
; another error is thatTextStyle.FULL
it is not the class you should use: you should useCalendar.LONG
.TestStyle
It works but for the classjava.time.Month;
, in this case for your example it is not necessary since it would involve extra steps to convert the month toMonth
and then get the name.I leave you an example with the 2 ways to obtain the name of the month using Calendar and Month:
Something to keep in mind is that the class
Calendar
belongs to the packagejava.util
and has many design errors: for example the number of the monthCalendar
starts at zero (0=January, 1=February ... 11=December) which is not intuitive .The class
Month
is from the packagejava.time
was introduced in Java 8, correcting the problems ofCalendar
andjava.util.Date
, so you must add 1 to get the correct monthMonth.of(numeroMes + 1);
because January is 1 injava.time
. The best thing is that you stop usingCalendar
it if possible and that you use the classes ofjava.time
only, they would beInstant, LocalDate y LocalDateTime
for the handling of date and time.