- Use the correct format which is
dd 'de' MMMM 'de' yyyy
for your date string.
- Always use
Locale
with date-time formatting/parsing API.
Demo:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdfInput = new SimpleDateFormat("dd 'de' MMMM 'de' yyyy", new Locale("es", "ES"));
Date date1 = sdfInput.parse("23 de marzo de 2021");
// Default string i.e. Date#toString implementation
System.out.println(date1);
// Custom string
SimpleDateFormat sdfOutput = new SimpleDateFormat("dd-MM-yyyy", new Locale("es", "ES"));
System.out.println(sdfOutput.format(date1));
}
}
Output:
Tue Mar 23 00:00:00 GMT 2021
23-03-2021
Note that the java.util
date-time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API* .
Using modern date-time API:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("dd 'de' MMMM 'de' uuuu", new Locale("es", "ES"));
LocalDate date1 = LocalDate.parse("23 de marzo de 2021", dtfInput);
// Default string i.e. LocalDate#toString implementation
System.out.println(date1);
// Custom string
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("dd-MM-uuuu", new Locale("es", "ES"));
System.out.println(dtfOutput.format(date1));
}
}
Output:
2021-03-23
23-03-2021
Learn more about the modern date-time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.