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

2

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

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

The method I use is this (I've actually simplified it to make it easier for those 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);

    }
}
    
asked by anonymous 18.03.2018 / 17:13

1 answer

5

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

Any type / class Date represents a specific time in time, with an accuracy of milliseconds. It does not have any format, it represents the number of milliseconds that ran from January 1, 1970 00:00:00 GMT.

The java.sql.Date class is a wrapper on java.util.Date , which allows JDBC to identify this (java.util.Date) as a SQL DATE value.

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

    
18.03.2018 / 17:34