springboot中获取当前日期
时间: 2023-11-21 07:55:22 浏览: 100
在Spring Boot中获取当前日期可以使用Java 8中的LocalDate和LocalDateTime类。可以使用以下代码获取当前日期和时间:
```java
import java.time.LocalDate;
import java.time.LocalDateTime;
public class DateUtils {
public static LocalDate getCurrentDate() {
return LocalDate.now();
}
public static LocalDateTime getCurrentDateTime() {
return LocalDateTime.now();
}
}
```
在上面的代码中,getCurrentDate()方法返回当前日期,getCurrentDateTime()方法返回当前日期和时间。这两个方法都使用Java 8中的now()方法来获取当前日期和时间。
相关问题
springboot怎么获取当天日期
在Spring Boot中,你可以使用Java的`java.time.LocalDate`类来获取当天日期。可以按照以下步骤进行操作:
1. 首先,确保你的项目中已经添加了`java.time`相关的依赖,如果没有,可以在`pom.xml`文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
```
2. 在你的代码中,导入`java.time.LocalDate`类:
```java
import java.time.LocalDate;
```
3. 使用`LocalDate.now()`方法获取当前日期:
```java
LocalDate currentDate = LocalDate.now();
```
现在,`currentDate`变量中就包含了当天的日期。你可以根据需要对其进行格式化、操作等操作。
springboot获取当前时间
在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`。