日期字符串转LocalDateTime
时间: 2023-11-14 14:09:02 浏览: 162
可以使用Java 8中的DateTimeFormatter类来将日期字符串转换为LocalDateTime对象。具体代码如下:
```java
String dateString = "2021-10-01 12:30:45";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
```
其中,第一个参数是待转换的日期字符串,第二个参数是日期格式化字符串。需要注意的是,日期格式化字符串中的字母必须与日期字符串中的字母一一对应。
相关问题
字符串转LocalDateTime
要将字符串转换为 LocalDateTime,您可以使用 `java.time.LocalDateTime` 类中的 `parse()` 方法。以下是一个示例:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String dateTimeString = "2021-10-15T10:30:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
System.out.println(dateTime);
}
}
```
在上面的示例中,我们首先定义了一个表示日期时间的字符串 `dateTimeString`,然后创建了一个 `DateTimeFormatter` 对象来指定字符串的格式(在这里使用了 ISO-8601 格式)。最后,我们使用 `parse()` 方法将字符串转换为 `LocalDateTime` 对象,并打印输出结果。
请注意,您需要根据实际的日期时间字符串格式来调整 `DateTimeFormatter` 中的模式字符串。
java字符串转localdatetime
你可以使用Java 8中的`DateTimeFormatter`类来将字符串转换为`LocalDateTime`对象。下面是一个示例代码:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String dateString = "2022-01-01 10:30:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
System.out.println(dateTime);
}
}
```
在上面的示例中,我们使用了`DateTimeFormatter`类来指定日期时间字符串的格式,然后使用`LocalDateTime.parse()`方法将字符串解析为`LocalDateTime`对象。最后,我们打印输出`LocalDateTime`对象的值。
请注意,日期时间字符串的格式必须与`DateTimeFormatter`中指定的格式完全匹配,否则会抛出异常。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)