DateTime format

I am trying to format the current datetime and then save it to the database using sleep mode. I got it to save using the default date format, that is:

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

I found a way to format it, but it is really messy 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); 
+1
java hibernate
Aug 21 '13 at 18:12
source share
1 answer

Try using 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 what you show, the date object actually has no changes. The only thing that happens: you create a String that contains the formatted date. Thus, you can specify a DateTimeFormat template to store the date in this template.

Also note that the string β€œhh” in your date pattern will actually give you a value from 1 to 12. This is AM / PM hour. To get a value of 0-24 hours, use "HH" instead (see http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html , "Date and Time Templates")

+1
Aug 21 '13 at 18:15
source share



All Articles