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

求助关于 LocalDateTime 的转换

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

    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 org.apache.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 啊
    uselessVisitor
        6
    uselessVisitor  
       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   ·   我们的愿景   ·   实用小工具   ·   3485 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 62ms · UTC 04:54 · PVG 12:54 · LAX 21:54 · JFK 00:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.