2013-08-21 369 views
1

我试图格式化当前datetime,然后使用Hibernate将它保存到数据库中。我得到了它使用的是默认的日期格式保存,即:格式日期时间

Date date = new Date(); 
hibernateObject.setDate(date); 
hibernateObject.save(date); 

我已经找到一种方法来格式化,但它确实不整洁,不似乎工作:

Date finalDate = null; 
try { 
    Date date = new Date(); 
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
    String sDate = df.format(date); 
    finalDate = df.parse(sDate); 
} catch (ParseException pe) { 
    System.out.println("ParserException while attempting to establish date"); 
} 
hibernateObject.setDate(date); 
hibernateObject.save(date); 
+0

哪些数据类型是你想存储日期? – Thierry

+0

数据库表列已设置为“DATETIME” – ThreaT

回答

2

尝试使用这个(在你的hibernateObject类中):

@Temporal(TemporalType.TIMESTAMP) 
@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss") 
public Date getStartDate() { 
    return startDate; 
} 
public void setStartDate(Date startDate) { 
    this.startDate = startDate; 
} 

当你做显示日期对象实际上没有改变。唯一发生的事情是:您创建包含格式化日期的字符串。因此,您可以指定DateTimeFormat模式来在该模式中存储日期。

还要注意,在你的日期模式“HH”字符串实际上会给你的价值从1到12这是AM/PM小时。为了获得0-24小时值中使用“HH”(请参阅​​第http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html,“日期和时间模式”一节)