LocalDateTime.now指定格式
时间: 2023-08-16 13:13:24 浏览: 55
要使用`LocalDateTime.now()`方法获取当前的本地日期和时间,然后将其格式化,可以使用`DateTimeFormatter`类来指定格式。
下面是一个示例代码,将当前的本地日期和时间格式化为"yyyy-MM-dd HH:mm:ss"格式:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime currentDateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = currentDateTime.format(formatter);
System.out.println("Formatted DateTime: " + formattedDateTime);
}
}
```
运行上述代码,将会输出类似以下格式的当前日期和时间:
```
Formatted DateTime: 2022-01-01 09:30:00
```
你可以根据需要修改`DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")`中的格式字符串来指定不同的格式。例如,如果你需要以"MM/dd/yyyy HH:mm:ss"格式显示日期和时间,可以将格式字符串改为`"MM/dd/yyyy HH:mm:ss"`。
希望这对你有所帮助!如果还有其他问题,请随时提问。