我在数据库中有日期字段,其值为"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;
}
}发布于 2014-03-10 15:55:28
默认情况下,数据库将存储您所在的时区。然而,在检索日期时,它不会添加回您所在的时区。该日期显示为GMT。看看如何使用JodaTime来获得更好的日期库。
我给你举个例子。您需要JodaTime库和JadiraTypes库来使用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;
这将持久化您的日期为您休眠。
我90%确定JodaTime支持为你添加回时区。如果您真的很担心,请将它们作为时间戳存储在数据库中。
尝试如上所述更改为JodaTime,如果有任何问题,请告诉我。
发布于 2014-03-10 21:19:35
我认为你应该在处理视图和控制器之间的日期时使用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));
}https://stackoverflow.com/questions/22294744
复制相似问题