springboot中获取当前时间
时间: 2024-01-03 21:22:52 浏览: 26
在Spring Boot中获取当前时间有多种方法,以下是其中两种常用的方法:
1. 使用Java的Date类获取当前时间:
```java
import java.util.Date;
public class MyController {
@GetMapping("/current-time")
public String getCurrentTime() {
Date currentTime = new Date();
return "Current time is: " + currentTime.toString();
}
}
```
2. 使用Java 8的LocalDateTime类获取当前时间:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class MyController {
@GetMapping("/current-time")
public String getCurrentTime() {
LocalDateTime currentTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedTime = currentTime.format(formatter);
return "Current time is: " + formattedTime;
}
}
```
以上两种方法都可以在Spring Boot的控制器类中使用,通过访问`/current-time`接口可以获取当前时间。