springboot获取当前时间
时间: 2023-10-13 18:19:04 浏览: 136
在Spring Boot中,你可以使用Java 8的新日期时间API来获取当前时间。以下是一个示例代码,可以获取当前时间并将其输出到控制台:
```java
import java.time.LocalDateTime;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TimeController {
@GetMapping("/current-time")
public String getCurrentTime() {
LocalDateTime currentTime = LocalDateTime.now();
return "Current time is: " + currentTime.toString();
}
}
```
在上面的代码中,我们使用`LocalDateTime.now()`方法获取当前时间,并将其格式化为字符串返回给调用者。我们还使用`@RestController`注解来将该类标记为一个RESTful服务,使用`@GetMapping`注解来指定该服务的路径为`/current-time`。
相关问题
springboot获取当前时间秒数
可以使用Java 8中的`Instant`类来获取当前时间的秒数。以下是一个示例代码:
```java
import java.time.Instant;
public class CurrentTimeInSeconds {
public static void main(String[] args) {
Instant instant = Instant.now();
long currentTimeInSeconds = instant.getEpochSecond();
System.out.println(currentTimeInSeconds);
}
}
```
运行上述代码将输出当前时间的秒数。
springboot获取当前时间的时分秒
在Spring Boot中,你可以使用Java的`LocalTime`类来获取当前时间的时分秒。以下是一个示例代码:
```java
import java.time.LocalTime;
public class TimeExample {
public static void main(String[] args) {
LocalTime currentTime = LocalTime.now();
int hour = currentTime.getHour();
int minute = currentTime.getMinute();
int second = currentTime.getSecond();
System.out.println("当前时间:" + hour + ":" + minute + ":" + second); }
}
```
在上面的代码中,我们使用`LocalTime.now()`方法获取当前时间,然后使用`getHour()`、`getMinute()`和`getSecond()`方法分别获取时、分和秒。最后,我们将这些值打印出来。
注意:在使用`LocalTime`类之前,你需要确保你的项目中已经引入了Java 8或更高版本的依赖。