String转Date问题

本文介绍了一种在SpringBoot项目中遇到的日期格式转换错误,并详细记录了使用FastJson替代Jackson来解决此问题的过程。

报错信息

未能将‘ java.lang.string’类型的属性值转换为‘ po.endtime’属性所需的类型‘ java.util.date’; 
嵌套异常为 org.springwork.core.convert.convert.converversionfailedexception: 
未能将[ java.lang.string ]类型转换为[@org ]类型。
值“2022-03-30”的 
springframework.format.annotation.datetimformat java.util.date; 嵌套异常是 
java.lang.illegalargumentexception: 值的解析尝试失败[2022-03-30]
"JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String "2022-02-28T16:12:00.000Z": Failed to deserialize java.time.LocalDateTime: 
(java.time.format.DateTimeParseException) Text '2022-02-28T16:12:00.000Z' could not be parsed at index 10; nested exception is 
com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "2022-02-28T16:12:00.000Z": Failed to 
deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2022-02-28T16:12:00.000Z' could not be parsed at index 10
 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 171] (through reference chain: 
 com.suzui.homework.entity.Homework["hbegindate"])"

加上@DateTimeFormat注解之后依然失败。

img

解决办法

使用fastjson替换springboot原本的jackson

添加依赖

image-20220330142723256

编写配置类

配置类中需要注意设置的日期格式
image-20220330142813064

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableWebMvc // 必须要有这个注解,否则报错
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setCharset(StandardCharsets.UTF_8);
        config.setDateFormat("yyyy-MM-dd HH:mm:ssS");
        config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
        fastJsonConverter.setFastJsonConfig(config);
        List<MediaType> list = new ArrayList<>();
        list.add(MediaType.APPLICATION_JSON);
        fastJsonConverter.setSupportedMediaTypes(list);
        converters.add(fastJsonConverter);
    }
}
<think>我们首先需要明确:在编程中,DateString之间的换是常见的操作,尤其是在处理日期显示、存储和解析时。 通常,我们会使用日期格式化类来进行换。在Java中,常用的类有SimpleDateFormat(旧版)和DateTimeFormatter(新版,Java 8及以上)。 由于问题没有指定语言,但根据常见性,这里使用Java进行示例。同时,考虑到新旧版本,我会分别给出两种方式。 一、使用SimpleDateFormat(旧版,适用于Java 7及以下) 1. Date String 2. String Date 二、使用DateTimeFormatter(新版,Java 8及以上) 1. LocalDate/LocalDateTime String(注意:Java 8的日期时间API中推荐使用LocalDate、LocalDateTime等代替Date) 2. String LocalDate/LocalDateTime 但是注意:问题中要求的是DateString换,而Java 8中通常使用新的API,但有时也需要与旧的Date类进行互操作。因此,我将分别展示: 方案1:使用传统的SimpleDateFormat(处理java.util.Date) 方案2:使用Java 8的DateTimeFormatter(处理java.time.LocalDate/LocalDateTime)以及如何与java.util.Date进行换。 由于问题没有指定具体日期时间类,这里将提供两种情况的示例。 首先,我们来看使用SimpleDateFormat进行换: 示例1:Date String ```java import java.text.SimpleDateFormat; import java.util.Date; public class DateToStringExample { public static void main(String[] args) { // 创建一个Date对象,表示当前时间 Date currentDate = new Date(); // 定义日期格式 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 将Date换为String String dateString = dateFormat.format(currentDate); System.out.println("当前时间: " + dateString); } } ``` 示例2:String Date ```java import java.text.SimpleDateFormat; import java.util.Date; public class StringToDateExample { public static void main(String[] args) { String dateString = "2023-11-03 14:30:00"; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { // 将String换为Date Date date = dateFormat.parse(dateString); System.out.println("换后的Date: " + date); } catch (Exception e) { e.printStackTrace(); } } } ``` 接下来,我们来看使用Java 8的日期时间API(推荐): 由于Java 8引入了新的日期时间API(在java.time包下),它提供了更强大和易用的功能。但是,如果我们需要与旧的Date进行交互,就需要进行换。 示例3:使用DateTimeFormatter将LocalDateTime换为String ```java import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class LocalDateTimeToStringExample { public static void main(String[] args) { // 获取当前日期时间 LocalDateTime now = LocalDateTime.now(); // 定义格式 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 换为字符串 String formattedDateTime = now.format(formatter); System.out.println("当前时间: " + formattedDateTime); } } ``` 示例4:使用DateTimeFormatter将String换为LocalDateTime ```java import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class StringToLocalDateTimeExample { public static void main(String[] args) { String dateString = "2023-11-03 14:30:00"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 解析字符串为LocalDateTime LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter); System.out.println("换后的LocalDateTime: " + dateTime); } } ``` 但是,如果我们需要在Date和新的API之间换,可以这样做: 示例5:Date与LocalDateTime的互 ```java import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; public class DateConversionExample { public static void main(String[] args) { // 1. Date LocalDateTime Date date = new Date(); // 将Date换为Instant,然后指定时区换为LocalDateTime LocalDateTime localDateTime = date.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDateTime(); System.out.println("Date -> LocalDateTime: " + localDateTime); // 2. LocalDateTime Date LocalDateTime now = LocalDateTime.now(); Date convertedDate = Date.from(now.atZone(ZoneId.systemDefault()).toInstant()); System.out.println("LocalDateTime -> Date: " + convertedDate); } } ``` 解释: 1. 使用SimpleDateFormat进行换时,需要注意模式字符串(如"yyyy-MM-dd HH:mm:ss")必须与输入字符串匹配,否则会抛出ParseException。 2. SimpleDateFormat是非线程安全的,所以在多线程环境下需要小心使用(通常每个线程创建自己的实例)。 3. Java 8的DateTimeFormatter是线程安全的,推荐使用。 4. 新的日期时间API(java.time包)提供了更清晰的类(如LocalDate、LocalTime、LocalDateTime等),并且设计更合理。 相关问题: §§相关问题§§: 1. Java中SimpleDateFormat是线程安全的吗?如果不是,如何在多线程环境下使用? 2. Java 8的DateTimeFormatter支持哪些常用的日期时间模式? 3. 在Java中如何计算两个日期之间的间隔(例如相差多少天)? 4. 如何将时间戳(例如Unix timestamp)换为Date或LocalDateTime? </think> 在编程中,日期和字符串之间的换是常见操作。以下是不同语言中的实现方案及解释: ### Java 实现 (推荐 Java 8+) ```java import java.time.*; import java.time.format.*; public class DateConverter { public static void main(String[] args) { // 1. Date -> String LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String dateString = now.format(formatter); System.out.println("Date to String: " + dateString); // 2. String -> Date String input = "2023-10-05 14:30:00"; LocalDateTime parsedDate = LocalDateTime.parse(input, formatter); System.out.println("String to Date: " + parsedDate); } } ``` **解释**: 1. 使用 `LocalDateTime` 表示日期时间,`DateTimeFormatter` 定义格式 2. `format()` 将日期为字符串 3. `parse()` 将字符串为日期 4. 格式模式说明: - `yyyy`:四位年份 - `MM`:两位月份 - `dd`:两位日期 - `HH`:24小时制小时 - `mm`:分钟 - `ss`:秒 ### Python 实现 ```python from datetime import datetime # 1. Date -> String now = datetime.now() date_string = now.strftime("%Y-%m-%d %H:%M:%S") print(f"Date to String: {date_string}") # 2. String -> Date input_str = "2023-10-05 14:30:00" parsed_date = datetime.strptime(input_str, "%Y-%m-%d %H:%M:%S") print(f"String to Date: {parsed_date}") ``` **解释**: 1. `strftime()`:日期格式化为字符串 2. `strptime()`:字符串解析为日期 3. 格式符号: - `%Y`:四位年份 - `%m`:两位月份 - `%d`:两位日期 - `%H`:24小时制小时 - `%M`:分钟 - `%S`:秒 ### JavaScript 实现 ```javascript // 1. Date -> String const now = new Date(); const dateString = now.toISOString(); // ISO 8601 格式 console.log(`Date to String: ${dateString}`); // 自定义格式 const formatted = `${now.getFullYear()}-${(now.getMonth()+1).toString().padStart(2,'0')}-${now.getDate().toString().padStart(2,'0')}`; console.log(`Custom Format: ${formatted}`); // 2. String -> Date const input = "2023-10-05T14:30:00Z"; const parsedDate = new Date(input); console.log(`String to Date: ${parsedDate}`); ``` **解释**: 1. `toISOString()` 生成标准 ISO 格式字符串 2. 手动拼接实现自定义格式 3. `Date` 构造函数直接解析字符串 ### 注意事项 1. **时区处理**: - Java:使用 `ZonedDateTime` 处理时区 - Python:用 `pytz` 库 - JS:注意浏览器本地时区影响 2. **格式匹配**:解析时格式必须与输入字符串完全匹配 3. **错误处理**:解析失败时需捕获异常(如 `ParseException` in Java
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值