Reputation: 59
I have spring rest service project and I am using JPA hibernate and I am facing a strange issue in my controller. Below is code snippet:
controller:
@RequestMapping(method = RequestMethod.POST, value=PATH_SEPERATOR+ CREATE_OR_UPDATE_EVENT_METHOD, headers = ACCEPT_APPLICATION_JSON, produces = APPLICATION_JSON)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
ResponseBean createOrUpdateEvent(@RequestBody Event eventBean)
{
ResponseBean response = new ResponseBean();
try {
String sysId = eventService.createOrUpdateEvent(eventBean);
response.setStatus(OK);
response.setData(sysId);
} catch(Exception ex) {
response = handleException(CREATE_OR_UPDATE_EVENT_METHOD, ex);
return response;
}
return response;
}
Event.java
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "sysId", scope = Event.class)
@Table(name = "event")
public class Event {
@Column(name = "date_time")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")
private Date dateTime;
public Date getDateTime() {
return dateTime;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
}
When I pass date to Event bean in createOrUpdateEvent
method as String "2014-04-17T17:15:56" which is in IST timezone, the controller convert it to Date with datetime "2014-04-17T22:45:56" IST considering previous time as UTC time. I don't understand this behaviour of auto conversion. I assume that it's because I am accepting parameter as bean, where bean is JPA Entity. Please help me to fix it.
Upvotes: 0
Views: 1915
Reputation: 589
There are several things you must take into consideration. First and foremost you are lacking a time zone information in the provided JSON serialization format "yyyy-MM-dd'T'HH:mm:ss". There's a format character that adds it - Z. Using it should be something like "yyyy-MM-dd'T'HH:mm:ssZ" depending on your preferences. Another thing you should consider is the fact that java.util.Date is not TimeZone aware and when you are creating a new Date(long) it always assumes that the passed date is in the current time zone.
So in order to fix this issue you have to add (and pass) the time zone as I told you and the Json parser will do the rest.
Upvotes: 1