2017-08-13 57 views
1

我使用Spring Boot,並嘗試在MongoDB中保存一些日期。我輸入的日期是無法使用Spring Boot將日期時間保存到MongoDB中

"2017-08-14T12:59"

我同時節省得到這個錯誤:

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Failed to parse Date value '2017-08-14T12:59': Can not parse date "2017-08-14T12:59.000Z": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Failed to parse Date value '2017-08-14T12:59': Can not parse date "2017-08-14T12:59.000Z": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null) (through reference chain: 

在我的POJO我想是這樣的:

@JsonDeserialize(using= CustomDateDeserialize.class) 
private Date inputDateTime; 

和我實現解串器是這樣的:

private SimpleDateFormat dateFormat = new SimpleDateFormat(
      "yyyy-MM-dd HH:mm"); 

    @Override 
    public Date deserialize(JsonParser paramJsonParser, 
      DeserializationContext paramDeserializationContext) 
      throws IOException, JsonProcessingException { 
     String str = paramJsonParser.getText().trim(); 
     try { 
      return dateFormat.parse(str); 
     } catch (ParseException e) { 

     } 
     return paramDeserializationContext.parseDate(str); 
    } 

什麼el我想念這裏嗎?任何幫助讚賞。

回答

0

您需要在您的反序列化器中修改格式。

SimpleDateFormat dateFormat = new SimpleDateFormat( 「yyyy-MM-dd'T'HH:mm」);

任何方式simpledatetimeformat不是線程安全的。如果你用java8使用DateTimeFormat。

+0

集提起我想這也是,但我得到JSON解析錯誤:無法解析日期值「2017-08 -14T12:59':無法解析日期「2017-08-14T12:59.000Z」:雖然它似乎符合格式'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'',解析失敗(leniency?null); – Rohitesh

0

你爲什麼不嘗試Instant

@Field("your_db_id_name") 
private Instant inputDateTime; 

public void setInputDateTime(Instant inputDateTime) { 
    this.inputDateTime = inputDateTime; 
} 

public void getInputDateTime() { 
    return inputDateTime; 
} 

您可以通過使用Instant.now()

+0

不錯的一個我會試試這個 – Rohitesh

+0

@Rohitesh如果這解決了你的問題upvote和標記爲正確的答案。這對其他人會有價值。 –

相關問題