格式化日期时间 [英] Format DateTime
问题描述
我正在尝试格式化当前的 datetime
,然后使用休眠将其保存到数据库中.我将其保存为默认日期格式,即:
I'm trying to format the current datetime
and then save it to a database using hibernate. I got it to save using the default date format, i.e.:
Date date = new Date();
hibernateObject.setDate(date);
hibernateObject.save(date);
我找到了一种格式化它的方法,但是它确实很不整洁,而且似乎不起作用:
I've found a way to format it but it's really untidy and doesn't seem to work:
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);
推荐答案
尝试使用此方法(在您的hibernateObject类中):
Try to use this (in your hibernateObject class):
@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模式以将日期存储在该模式中.
When you do as you show date object actually has no changes. Only thing that happens: you create String that contains formatted date. So you can specify DateTimeFormat pattern to store date in that pattern instead.
还请注意,日期模式中的"hh"字符串实际上将为您提供1到12之间的值.这是AM/PM小时.要获取0-24小时的值,请改用"HH"(请参见 http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html ,日期和时间模式"部分)
Also note, that "hh" string in your date pattern actually will give you value from 1 to 12. It is AM/PM hour. To get 0-24 hours value use "HH" instead (see http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html, "Date and Time Patterns" section)
这篇关于格式化日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!