我在数据库中有日期字段,其值为"27-AUG-10 15:30:00"。我使用JPA来检索和设置模型对象。在模型对象中,日期是额外的一天"2010-08-28 04:00:00.0"。当检索的日期应该是2010年8月27日,但它是2010年8月28日,你能告诉我为什么检索额外的一天吗?
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;
}
}
默认情况下数据库将存储您所在的时区。但是,在检索日期时,它不会添加回您所在的时区。该日期显示为GMT。看看使用JodaTime作为一个更好的日期库。
我给你举个例子。您需要JodaTime库和jadirattypes库来使用Hibernate持久化JodaTime日期。 http://mvnrepository.com/artifact/joda-time/joda-time/2.3
http://mvnrepository.com/artifact/org.jadira.usertype/usertype.jodatime/2.0.1
你的代码看起来像这样:
@Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime date;
这将为你保存你的日期到Hibernate。
我90%确定JodaTime支持为您添加回时区。如果您真的担心,可以将它们作为时间戳存储在数据库中。
尝试将JodaTime更改为如上所述,如果有任何问题请告诉我
我认为你应该使用InitBinder当你玩的日期之间的视图和控制器
只需在控制器中输入以下内容
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}