java.time
The answer by Phaelax z is spot-on for your specific requirement.
However, I recommend you parse the date string to LocalDate
and format it as you wish.
You will get much more than the required conversion e.g. just think of finding the name of the day on 06-21-2020 or something like converting to some other format e.g. Sun 21 June 2020. All such requirements can be easily done using the in-built API as shown in the following demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String nDate = "06-21-2020";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("MM-dd-uuuu", Locale.ENGLISH);
LocalDate date = LocalDate.parse(nDate, dtfInput);
DateTimeFormatter dtfOutput1 = DateTimeFormatter.ofPattern("MMdduuuu", Locale.ENGLISH);
DateTimeFormatter dtfOutput2 = DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ENGLISH);
DateTimeFormatter dtfOutput3 = DateTimeFormatter.ofPattern("EEE dd MMM uuuu", Locale.ENGLISH);
System.out.println(dtfOutput1.format(date));
System.out.println(dtfOutput2.format(date));
System.out.println(dtfOutput3.format(date));
}
}
Output:
06212020
21/06/2020
Sun 21 Jun 2020
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
'-'
with nothing. UsereplaceAll
instead.LocalDate
for a date (like you useint
orlong
for an integer). See the answer by Arvind Kumar Avinash.