简体   繁体   中英

JPA java.util.Date issue

I have date field in the database where the value is "27-AUG-10 15:30:00". I am using JPA to retrieve and set into a model object. In the model object the date is one day extra "2010-08-28 04:00:00.0". When retrieved the date should be 27 Aug 2010, but it is coming 28 Aug 2010 Can you please suggest me why it is retrieving one extra day.

 import java.util.Date;
 import javax.persistence.Column;
public class Model
{
    @Column(name = "BEGIN_DATE")
private Date startDate;

    public Date getStartDate() {
    return startDate;
}

public void setStartDate(Date startDate) {
    this.startDate = startDate;
}

 }

The database will by default store the timezone you are in. However in retriving the date out it won't add back the timezone you are in. That date is being displayed as GMT. Look at using JodaTime for a better Date library.

I'll give you an example. You need the JodaTime library and the JadiraTypes library to persist JodaTime dates with Hibernate.

http://mvnrepository.com/artifact/joda-time/joda-time/2.3
http://mvnrepository.com/artifact/org.jadira.usertype/usertype.jodatime/2.0.1

Your code will look something like this:

@Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime") private LocalDateTime date;

This will persist your dates to Hibernate for you.

I'm 90% sure that JodaTime supports adding back the timezone for you. If you are really worried, store them as Timestamps in your database.

Try changing to JodaTime as above and let me know if you have any issues.

I think You should use InitBinder whenever you play with dates between view and controller.

Just put following in your controller

@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);
    webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM