joda,jackson,hibernate中的日期时间格式

时间:2014-05-19 13:35:38

标签: spring hibernate spring-mvc jackson jodatime

如何在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 ) { ..

我的Spring控制器总是在反序列化eventDateTime中失败,所以我得到响应错误400"客户端发送的请求语法错误"。

如果我将日期时间格式更改为:

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

它有效。

1 个答案:

答案 0 :(得分:0)

您的{"eventDateTime": "2014-05-19T14:8"}示例的工作原因是它采用ISO 8601日期格式。我建议您将日期时间格式设置为ISO 8601标准,因为您已经看到杰克逊可以处理它。

我猜你正在检索这个并用JavaScript将它发回服务器。如果是这样,你应该知道JS可以解析一个日期,只要它是几种格式之一。 (具体请参见the Date object和dateString参数)然后,您可以使用JavaScript格式化它,无论您想要显示它。

只要JavaScript知道它是一个日期,它应该以一种它能识别的格式将它发送回杰克逊(不确定自纪元以来的毫秒数,ISO 8601还是它的工作原理)。如果JavaScript将日期视为字符串,那么它会将其作为字符串传回,而杰克逊可能不知道如何处理它。

您可以使用JsonDeserializer强制杰克逊处理自定义日期格式。有关如何实施的详细信息,请参阅https://stackoverflow.com/a/5598277/965150