localdatetime格式化成字符串
时间: 2023-08-26 14:03:55 浏览: 89
你可以使用Java的DateTimeFormatter类将LocalDateTime格式化为字符串。下面是一个示例代码:
```
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeExample {
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("Formatted LocalDateTime: " + formattedDateTime);
}
}
```
在上面的示例中,我们使用now()方法获取当前的LocalDateTime对象。然后,我们使用DateTimeFormatter类中的ofPattern()方法创建一个格式化模板,指定如何格式化日期时间。最后,我们使用LocalDateTime对象的format()方法将其格式化为字符串,并将其存储在formattedDateTime变量中。最后,我们将格式化的日期时间字符串打印到控制台。