Make the java object.sql.Date have the format dd / MM / yyyy [duplicate]

this question already has answers here : format data in java (2 responses) Closed there 2 years .

I have a field that is of type String, where a data is typed in the format dd/MM/yyyy, I am converting to java.sql.Date, the result is: 2018-01-01.

What I needed was to get the date in format: dd/MM/yyyy, which would be :01/01/2018, but it needs to be in format data, not String, is it possible?

The method I use is this( I actually simplified it to make it easier for anyone who can help by running the code):

  public class NewClass {

    public static void main(String[] args) throws ParseException {
        String dataInicialString = "01/01/2018";
        String dataFinalString = "14/05/2018";
        DateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
        java.sql.Date dataInicial = null;
        java.sql.Date dataFinal = null;

        dataInicial = new java.sql.Date(fmt.parse(dataInicialString).getTime());

        dataFinal = new java.sql.Date(fmt.parse(dataFinalString).getTime());

        System.out.println("DATAINICIAL:" + dataInicial);
        System.out.println("DATAFINAL:" + dataFinal);

    }
}
 2
Author: ramaral, 2018-03-18

1 answers

There is no way to change the format, Date has no format.

Any type / class Date represents a specific instant in time, with millisecond accuracy. It does not have any format, it represents the number of milliseconds that has elapsed since January 1, 1970 00: 00: 00.000 GMT.

A Class java.sql.Date is a wrapper over java.useful.Date , which allows JDBC to identify this (java.useful.Date) as a SQL DATE value.

In the code you put in the question, when using System.out.println("DATAINICIAL:" + dataInicial); What is being done is a call to the toString() method that returns a string represented the value in the format yyyy-mm-dd.
If this is the case, you can overwrite the method so that it returns another format.
Note that overwriting the toString() method can bring problems since "others" may depend on the default implementation.

 5
Author: ramaral, 2018-03-19 16:50:55