Learthgz
Learthgz

Reputation: 133

Timestamp invalid hour in Java

I am using JPA with my Java project, and the timestamp is not working very well : it only shows 2015-08-12 00:00:00.0 (the day is correct but the hour is not)

@Entity
public class Session implements Serializable {

..
    @Temporal(TemporalType.DATE)
    private Date timestamp;
..

    public Session(String sessionId) {
        super();
        this.sessionId = sessionId;
        this.timestamp = new Date();
    }

    public Session() {
        super();
        this.timestamp = new Date();
    }

}

Do you know how to fix this?

Upvotes: 1

Views: 506

Answers (1)

Olimpiu POP
Olimpiu POP

Reputation: 5067

You should use TemporalType.TIMESTAMP that will map the field to a java.sql.Timestamp, hence it will contain also time related info, not only regarding date. In comparison, the type you used, TemporalType.DATE are mapped to java.sql.Date, class containing information like day, month year.

So, your code will transform in:

@Entity
public class Session implements Serializable {

   ..
   @Temporal(TemporalType.TIMESTAMP)
   private Date timestamp;
   ..

   public Session(String sessionId) {
       this.sessionId = sessionId;
       this.timestamp = new Date();
   }

   public Session() {
       this.timestamp = new Date();
   }
}

Upvotes: 4

Related Questions