The mistake is that the method format
gets a Date
, but you’re going through a String
.
And actually the conversion should not be done this way. If you have a String
in one format and want to convert to another format, first must convert this String
for a Date
, and then convert this Date
to the other format:
SimpleDateFormat formatoOrigem = new SimpleDateFormat("dd-MM-yyyy");
Date data = formatoOrigem.parse("10-03-2020"); // string com a data no formato dia-mês-ano
SimpleDateFormat formatoDestino = new SimpleDateFormat("yyyy-MM-dd");
String formatoAnoMesDia = formatoDestino.format(data);
Just to make it a little clearer, as I’ve said here, here and here, dates have no format.
A date is just a concept, an idea: it represents a specific point in the calendar.
The date of "1 January 1970", for example, represents this: the specific point of the calendar that corresponds to the first day of January 1970. To express this idea in text form, I can write it in different ways:
- 01/01/1970 (a common format in many countries, including Brazil)
- 1/1/1970 (American format, reversing day and month)
- 1970-01-01 (the format ISO 8601)
- First of January 1970 (in good Portuguese)
- January 1st, 1970 (in English)
- 1970 年 1 月 1 日 (in Japanese)
- and many others...
Note that each of the above formats is different, but all represent the same date (the same numerical values of the day, month and year).
That being said, a string like "10/03/2020" is not a date. It’s just a text that represents the date in a specific format, but it’s not the date itself. In Java, texts are represented by a String
and dates may be represented by a Date
.
When you want to turn one String
in a Date
, is making a Parsing. When you want to turn one Date
in a String
, is making a formatting. Hence the method parse
receives a String
and returns a Date
, and format
does the opposite. That is why the conversion of a String
in one format to another String
in another format should be done in 2 steps.
Another alternative is to use the API java.time
(here has instructions to use it on Android).
The idea is similar, first we need to transform the String
on a date (in case, in a LocalDate
, which is a class representing a date containing only day, month and year), and then we turn the date into another String
, in the desired format:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
...
DateTimeFormatter formatoOrigem = DateTimeFormatter.ofPattern("dd-MM-uuuu");
LocalDate data = LocalDate.parse("10-03-2020", formatoOrigem);
String formatoAnoMesDia = DateTimeFormatter.ISO_DATE.format(data);
// no caso do formato yyyy-MM-dd, toString() também funciona
// String formatoAnoMesDia = data.toString();
// ou ainda DateTimeFormatter.ofPattern("uuuu-MM-dd") - mas eu prefiro usar o que já existe pronto na API
System.out.println(formatoAnoMesDia);