求助关于 LocalDateTime 的转换

2021-03-12 10:40:39 +08:00
 saigo

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

2026 次点击
所在节点    Java
7 条回复
watermelon11
2021-03-12 10:42:25 +08:00
com.fasterxml.jackson.databind.util.Converter
aguesuka
2021-03-12 10:58:13 +08:00
加上时分秒。
这里就不该用注解
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
2021-03-12 11:48:41 +08:00
DateTime 你只给 Date 肯定报错啊……
要么把 Time 也传了,要么换 Date
xuanbg
2021-03-12 11:57:12 +08:00
LocalDateTime 改成 LocalDate 啊
uselessVisitor
2021-03-12 13:35:06 +08:00
LocalDateTime 必须有时分秒的,建议用 LocalDate 或者用 Date 接收
cslive
2021-03-12 14:35:35 +08:00
LocalDateTime 必须要有 time 不然被格式化异常,要么就用 Date 或者 LocalDate 完事

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/760943

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX