According to the documentation, for the month you should use the uppercase "M". The lowercase "m" is minutes.
Then I would be:
DateFormat formatUS = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatUS.parse(dataNotaFiscal);
DateFormat formatBR = new SimpleDateFormat("dd-MM-yyyy");
String dataConvertida = formatBR.format(date);
One detail is that SimpleDateFormat
is very permissive and accepts invalid dates such as "2020-99-99" (and the results are quite "weird", read more here and here). To avoid these cases, you can set the lenient mode to false
:
DateFormat formatUS = new SimpleDateFormat("yyyy-MM-dd");
formatUS.setLenient(false); // assim não aceita datas inválidas
Date date = formatUS.parse(dataNotaFiscal);
... etc
This way, invalid dates will make an exception.
If you are using Java >= 8, another option is to use the API java.time
. For your case, which has only day, month and year, can be used a java.time.LocalDate
, and to format, use a java.time.format.DateTimeFormatter
:
LocalDate data = LocalDate.parse(dataNotaFiscal);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-uuuu");
String dataConvertida = fmt.format(data);
Detail that method parse
by default already works with the format "year-month-day" (which is the format defined by ISO 8601 standard). But if the string was in another format, just create another DateTimeFormatter
and pass it to the method parse
. Ex:
// supondo que a string está em outro formato
DateTimeFormatter parser = DateTimeFormatter.ofPattern("dd/MM/uuuu")
.withResolverStyle(ResolverStyle.STRICT); // para não aceitar datas inválidas
LocalDate data = LocalDate.parse("20/01/2020", parser);
etc..
Also note the use of "u" instead of "y" for the year. For more details, see here.
As to the use of ResolverStyle
, it is because of default the parser accepts some invalid dates, such as 31/04/2020 (as April only has 30 days). See more details in replies of this question.
managed to settle here with your tips! Thank you very much!!
– Paula Mz