Retreving date from Hibernate TImestamp
I have a field with temporal type as Timestamp to save both date and time to the database.
@Temporal(TemporalType.TIMESTAMP)
@Column(name="date", nullable=false)
private Date date;
But when displaying the value to the user, I just want to show date part and truncate time part. I tried this but I get ParseException probably because of the Nanosecond part of the Hibernate Timestamp.
SimplDateFormat sd = new SimpleDateFormat("开发者_StackOverflow中文版MM/dd/yyyy");
return sd.parse(date.toString());
So how do I retrieve just date from Hibernate Timestamp? Thanks
Just format the date object. The toString
method isn't guaranteed to give you a string in a format that can then be parsed.
String dateStr = sd.format(date);
That will give you a date string in MM/dd/yyyy format that you can then convert back into a Date.
Date fancyNancy = sd.parse(dateStr);
* EDIT *
Run this code and verify it prints out the day, month and year with no time.
try {
Date d = new Date();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Original Date: " + d);
System.out.println("Formatted Date: " + df.parse(df.format(d)));
} catch (Exception e) {
e.printStackTrace();
}
精彩评论