You can use the SimpleDateFormat class to format it like this:
//Aquí colocas tu objeto tipo Date
Date myDate = new Date();
//Aquí obtienes el formato que deseas
System.out.println(new SimpleDateFormat("dd-MM-yyyy").format(myDate));
If you have any other questions, you can consult the documentation of this class here
Although your exercise asks for a Date , it's good to know that we are beginning to migrate from Java 8 to the javax.time date libraries and instead of Date use the LocalDate object .
Date fecha = Date();
LocalDate fecha1 = LocalDate.now();
LocalDate fecha2 = LocalDate.of(año,mes,dia);
public String getFechaMod(){
SimpleDateFormat sf = new SimpleDateFormat("dd-MM-yyyy");
return sf.format(fechaMod);
}
We create a method of type string. We declare simpledateformatwhich lets us customize the format in which we want to display the date as shown in this example .
public Date devolverFecha(Date fechaEntrada) {
SimpleDateFormat formato = SimpleDateFormat("dd/M/yyyy");
String fechaString = fechaEntrada.toString(); // Convierte Date a String
Date miFecha = formato.parse(fechaString); // convierte String a Date
return miFecha;
}
You can use the SimpleDateFormat class to format it like this:
If you have any other questions, you can consult the documentation of this class here
PS: This question is answered in English here .
Although your exercise asks for a Date , it's good to know that we are beginning to migrate from Java 8 to the javax.time date libraries and instead of Date use the LocalDate object .
Links of interest
Try with
SimpleDateFormat();
that you can give it the format you like.Example:
To call the function:
The MM in uppercase if you put it in lowercase it takes it as a minute.
You can do the following:
We create a method of type string. We declare
simpledateformat
which lets us customize the format in which we want to display the date as shown in this example .If the method would look like this:
This is a proposed solution