0

How to set datetime formatting in joda, jackson, hibernate.

import org.joda.time.DateTime;
import com.fasterxml.jackson.annotation.JsonFormat;
//other imports...

@Entity
public class Example {

    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")   
    @JsonFormat(pattern = "dd/MM/yyyy'T'HH:mm")
    private DateTime eventDateTime;     

//getters setters
}


//registration joda jackson module:
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.registerModule(new JodaModule());
  objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
  DateFormat df = new SimpleDateFormat("dd/MM/yyyy'T'HH:mm");        
  objectMapper.setDateFormat(df); 


//If I send JSON like:
{"eventDateTime": "19/05/2014T14:8"}

//my spring controller:
@RequestMapping(method = RequestMethod.POST)    
    public void saveExample(@RequestBody Example example ) { ..

My Spring controller always fails in de-serialization eventDateTime so I'm getting response error 400 "The request sent by the client was syntactically incorrect".

If I change datetime formatting to:

{"eventDateTime": "2014-05-19T14:8"}

and it works.

Steve P
  • 162
  • 1
  • 11
mark small
  • 137
  • 3
  • 12

1 Answers1

0

The reason your {"eventDateTime": "2014-05-19T14:8"} example works is that it's in the ISO 8601 date format. I would recommend setting your datetime format to the ISO 8601 standard since you've already seen that Jackson can handle it.

I'm guessing that you're retrieving this and sending it back to the server with JavaScript. If so, you should know that JS can parse a date as long as it's in one of a few formats. (see the Date object and the dateString parameter in particular) Then you can use JavaScript to format it however you want for display.

As long as JavaScript knows it's a Date, it should send it back to Jackson in a format it can recognize (not sure if that's milliseconds since the epoch, ISO 8601 or what but it works). If JavaScript treats the date as a string then it will pass it back as a string and Jackson will probably not know what to do with it.

You can force Jackson to handle a custom date format by using a JsonDeserializer. See https://stackoverflow.com/a/5598277/965150 for details on how that would be implemented.

Community
  • 1
  • 1
Planky
  • 3,185
  • 3
  • 29
  • 39
  • I need "dd/MM/yyyy" formatted date from the reason jquery plugin, which doesn't work with "yyyy-MM-dd" and any transforming in javascript between formats is waste. – mark small May 19 '14 at 18:02
  • I think that problem is in integration netween joda and jackson, because @JsonFormat(pattern = "dd/MM/yyyy'T'HH:mm") works on java.util.Date type. – mark small May 19 '14 at 18:12
  • As I mentioned at the end of my answer, try the JsonDeserializer which takes a generic. You can specify any conversion strategy you like for your joda DateTime object. – Planky May 19 '14 at 19:03