1

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); 
2
  • What data type are you trying to store the date as? Commented Aug 22, 2013 at 20:51
  • The DB table column was set to DATETIME Commented Aug 23, 2013 at 6:25

1 Answer 1

3

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; } 

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.

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)

Sign up to request clarification or add additional context in comments.

Comments