`java.util.Date` from String "2021-09-08 16:22:10.000": expected format "yyyy-MM-dd HH:mm:ss:SSS";
时间: 2024-09-20 07:11:15 浏览: 78
当你尝试使用 `java.util.Date` 类从字符串 "2021-09-08 16:22:10.000" 构造一个日期对象,但指定的格式不是 "yyyy-MM-dd HH:mm:ss:SSS",这将导致解析错误。`Date` 类默认解析的是 "yyyy.MM.dd G 'at' HH:mm:ss z" 的格式,其中包含了一些固定的分隔符。如果你提供的字符串按照 ISO 8601 格式,即 "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 或 "yyyyMMdd'T'HHmmss'Z'",那么可以直接解析。
正确的做法应该是先使用 `SimpleDateFormat` 或 `DateTimeFormatter` 将字符串转换为 `Date` 对象,传入正确的日期时间格式。例如:
```java
String dateString = "2021-09-08 16:22:10.000";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
try {
Date date = sdf.parse(dateString);
} catch (ParseException e) {
// 处理解析异常
}
```
相关问题
`java.util.Date` from String 2021-07-28 21:36:34: not a valid representation
The error message you are seeing suggests that the string you are trying to parse into a `java.util.Date` object is not in a valid format.
By default, `java.util.Date` expects the input string to be in the format of "EEE MMM dd HH:mm:ss zzz yyyy". If the input string does not match this format, you will get a `ParseException`.
To parse a string in a different format, you can use a `SimpleDateFormat` object to specify the input format. Here's an example:
```
String dateString = "2021-07-28 21:36:34";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormat.parse(dateString);
```
This code creates a `SimpleDateFormat` object with the format "yyyy-MM-dd HH:mm:ss", which matches the format of the input string. It then calls the `parse` method on the `dateFormat` object to convert the string into a `Date` object.
Note that the `parse` method can also throw a `ParseException` if the input string does not match the specified format. You may want to handle this exception to provide a better error message to the user.
jackson Cannot deserialize value of type java.util.Date from String "2023-01-16 09:48:12"
这个错误消息表明,Jackson在尝试将字符串 "2023-01-16 09:48:12" 反序列化为java.util.Date类型时出错。这可能是由于字符串的格式不符合Jackson预期的格式造成的。应该检查字符串是否符合Jackson预期的日期格式,并确保它能被正确解析。
阅读全文