Make java.sql.Date object to dd/MM/yyyy format

Asked

Viewed 936 times

2

I got a field that’s like String, where a data in 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 format data, nay String, it is possible?

The method I use is this( ):

  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);

    }
}

1 answer

5

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

Any Date type/class represents a specific instant in time, with an accuracy of milliseconds. It has no format, represents the number of milliseconds that ran since January 1, 1970 00: 00: 00.000 GMT.

The class java.sql.Date is a wrapper about java.util.Date, which allows JDBC to identify this(java.util.Date) as an 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 method toString() which returns a string represented the value in the format yyyy-mm-dd.
If the use is this can override the method so that it returns another format.
Please note that the method envelope toString() can cause problems since "others" may depend on the standard implementation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.