LocalDateTime 转字符串
时间: 2023-11-11 08:57:55 浏览: 43
要将 LocalDateTime 对象转换为字符串,可以使用 DateTimeFormatter 类的 format 方法。以下是示例代码:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// 创建 LocalDateTime 对象
LocalDateTime dateTime = LocalDateTime.now();
// 创建格式化器
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 转换为字符串
String formattedDateTime = dateTime.format(formatter);
System.out.println(formattedDateTime);
}
}
```
这段代码将 LocalDateTime 对象转换为了形如 "2022-01-01 12:30:45" 的字符串。
相关问题
LocalDateTime转字符串
要将LocalDateTime类型的日期对象转换为字符串,可以使用DateTimeFormatter类的ofPattern方法指定日期格式,然后使用format方法将日期对象转换为字符串。例如,可以使用以下代码将LocalDateTime对象转换为字符串:
```java
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateTimeStr = dateTime.format(formatter);
```
其中,dateTime是LocalDateTime类型的日期对象,formatter是指定的日期格式,dateTimeStr是转换后的字符串表示日期时间。最后,可以使用println方法将结果打印出来。
引用<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [LocalDateTime、LocalDate、Date、String相互转化大全及其注意事项](https://blog.csdn.net/BASK2312/article/details/131419428)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
localdatetime转字符串
要将LocalDateTime转换为字符串,可以使用DateTimeFormatter类来指定日期时间的格式。以下是一个例子:
```
LocalDateTime localDateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String localDateTimeStr = localDateTime.format(formatter);
System.out.println(localDateTimeStr);
```
这段代码将当前的LocalDateTime对象转换为字符串形式,使用的日期时间格式是"yyyy-MM-dd HH:mm:ss"。你可以根据需要自定义日期时间的格式。