【问题标题】:Cannot save datetime to MongoDB using Spring Boot无法使用 Spring Boot 将日期时间保存到 MongoDB
【发布时间】:2017-08-13 07:43:05
【问题描述】:

我使用 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);
    }

我还想念什么?任何帮助表示赞赏。

【问题讨论】:

    标签: java mongodb spring-boot


    【解决方案1】:

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

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

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

    【讨论】:

    • 我也试过了,但我收到 JSON 解析错误:无法解析日期值“2017-08-14T12:59”:无法解析日期“2017-08-14T12:59.000Z”:虽然它似乎适合格式 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'',但解析失败(宽容?null);
    【解决方案2】:

    你为什么不试试Instant

    @Field("your_db_id_name")
    private Instant inputDateTime;
    
    public void setInputDateTime(Instant inputDateTime) {
        this.inputDateTime = inputDateTime;
    }
    
    public void getInputDateTime() {
         return inputDateTime;
    }
    

    您可以使用Instant.now()设置归档

    【讨论】:

    • 不错的我会试试这个
    • @Rohitesh 如果这解决了您的问题,请投票并标记为正确答案。这对其他人来说很有价值。
    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多