求助关于 LocalDateTime 的转换 - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
saigo
V2EX    Java

求助关于 LocalDateTime 的转换

  •  
  •   saigo 2021-03-12 10:40:39 +08:00 2824 次点击
    这是一个创建于 1723 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Model

     @ApiModelProperty(value = "日期") @JsonFormat(pattern = "yyyy-MM-dd", shape = JsonFormat.Shape.STRING) @DateTimeFormat(pattern = "yyyy-MM-dd") private LocalDateTime dataTime; 

    用的代码生成器,所有的日期类型都是 LocalDateTime,其实这个地方用 LocalDate 就可以了

    请求

    { "dataTime":"2021-03-12" } 

    错误

    { "code": 1, "msg": "JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String \"2021-03-12\": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2021-03-12' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2021-03-12 of type java.time.format.Parsed; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String \"2021-03-12\": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2021-03-12' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2021-03-12 of type java.time.format.Parsed\n at [Source: (PushbackInputStream); line: 2, column: 16] (through reference chain: com.qctc.bdss.marketanalysis.entity.MarketLineBlockAhead[\"dataTime\"])", "data": null } 

    请问怎么通过注解的方式将 yyyy-MM-dd 格式的字符串转换为 LocalDateTime

    7 条回复    2021-03-12 14:35:35 +08:00
    watermelon11
        1
    watermelon11  
       2021-03-12 10:42:25 +08:00
    com.fasterxml.jackson.databind.util.Converter
    aguesuka
        2
    aguesuka  
       2021-03-12 10:58:13 +08:00 via Android
    加上时分秒。
    这里就不该用注解
    jorneyr
        3
    jorneyr  
       2021-03-12 11:00:02 +08:00
    写一个 Converter: http://qtdebug.com/html/spring-boot/Converter.html

    参考下面这段代码

    ```java
    package com.xtuer.converter;

    import lombok.extern.slf4j.Slf4j;
    import orgapache.commons.lang3.StringUtils;
    import org.springframework.core.convert.converter.Converter;

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    /**
    * 把日期字符串转换为 Date 对象。
    */
    @Slf4j
    public final class DateConverter implements Converter<String, Date> {
    // 使用 ThreadLocal 解决 SimpleDateFormat 高并发问题
    private static final ThreadLocal<SimpleDateFormat> FORMAT_1 = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
    private static final ThreadLocal<SimpleDateFormat> FORMAT_2 = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    private static final ThreadLocal<SimpleDateFormat> FORMAT_3 = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));

    /**
    * 把日期字符串转换为 Date 对象,接收三种日期格式: yyyy-MM-dd 、yyyy-MM-dd HH:mm:ss 或者 yyyy-MM-ddTHH:mm:ss.SZ
    * 如果日期的格式不对,则返回 null 。
    *
    * @param source 字符串格式的日期
    * @return 返回日期 Date 的对象,如果日期的格式不对,则返回 null 。
    */
    @Override
    public Date convert(String source) {
    if (StringUtils.isBlank(source)) {
    return null;
    }

    SimpleDateFormat format = null;

    switch (StringUtils.length(source)) {
    case 10: format = FORMAT_1.get(); break;
    case 19: format = FORMAT_2.get(); break;
    case 24: format = FORMAT_3.get(); break;
    default:
    log.warn("日期格式不对: {}", source);
    return null;
    }

    try {
    return format.parse(source);
    } catch (ParseException ex) {
    log.warn(ex.getMessage());
    }

    return null;
    }
    }

    ```
    chendy
        4
    chendy  
       2021-03-12 11:48:41 +08:00
    DateTime 你只给 Date 肯定报错啊……
    要么把 Time 也传了,要么换 Date
    xuanbg
        5
    xuanbg  
       2021-03-12 11:57:12 +08:00
    LocalDateTime 改成 LocalDate 啊
    zm8m93Q1e5otOC69
        6
    zm8m93Q1e5otOC69  
       2021-03-12 13:35:06 +08:00
    LocalDateTime 必须有时分秒的,建议用 LocalDate 或者用 Date 接收
    cslive
        7
    cslive  
       2021-03-12 14:35:35 +08:00
    LocalDateTime 必须要有 time 不然被格式化异常,要么就用 Date 或者 LocalDate 完事
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     939 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 28ms UTC 23:30 PVG 07:30 LAX 15:30 JFK 18:30
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86