Problem with Java Timestamp with SQL Date type

1.8k views Asked by At

In my db table I have a column c_dob of Type date

For my controller Request class, I use the above field like this :

import java.sql.Timestamp;
public class UpdateUserProfileRequest {

    private Timestamp dob;
    public Timestamp getDob() {
        return dob;
    }
    public void setDob(Timestamp dob) {
        this.dob = dob;
    }
}

Problems :

  • What happens is when I have the value 1979-06-30 passed as a request json value, in the controller class, the request class logs the value as 1979-06-30 02:00:00.0 (hour part is added and given a value on its own)

  • Second, for setting the dob the following code I am using :

    Map<String, Object> outMap = proc.execute(inParams);       
    profile.setDob((Date) outMap.get("out_dob") != null
                             ? new Timestamp(((Date) outMap.get("out_dob")).getTime()) : null);
    

And what happens here is that 1979-06-30 02:00:00.0 is changed to 1979-06-30 01:00:00.0 which causes logical problem.

So, is there any reason or any solution for this behavior?

Edit : Database is MySql

2

There are 2 answers

0
Basil Bourque On

You are using the wrong data types. The MySQL type DATE represents a date-only value, without time-of-day and without time zone. In contrast, the java.sql.Timestamp class represents a moment, a specific point on the timeline, a date with time-of-day as seen in UTC. Square peg, round hole.

Use only java.time classes. Never use the terrible legacy date-time classes such as Timestamp.

For MySQL DATE use java.time.LocalDate with a JDBC driver that complies with JDBC 4.2 or later.

LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;
1
Bernd Farka On

Make use of java.time.LocalDateTime which is timezone aware and should help you a lot...

java.sql.Timestamp is a terrible and some leftover of the dark ages :)