springboot获取当前时间戳timestamp
时间: 2023-11-11 21:59:59 浏览: 187
可以使用Java 8的LocalDateTime类获取当前时间戳,示例代码如下:
```
import java.time.LocalDateTime;
import java.time.ZoneOffset;
public class Demo {
public static void main(String[] args) {
long timestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
System.out.println(timestamp);
}
}
```
相关问题
springboot 获取时间戳
在Spring Boot中,获取当前的时间戳通常通过`java.time.LocalDateTime`或`java.util.Date`类来实现。这里是一个简单的例子:
1. 使用`LocalDateTime`:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class TimestampExample {
public LocalDateTime getCurrentTimestamp() {
return LocalDateTime.now(); // 获取当前日期和时间
}
public String formatTimestampToHumanReadable() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDateTime.now().format(formatter); // 格式化为字符串如"2023-04-01 15:30:00"
}
}
```
2. 使用`Date`(请注意,`java.util.Date`已被标记为过时,推荐使用`LocalDateTime`):
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class OldTimestampExample {
public Date getCurrentTimestamp() {
return new Date();
}
public String formatTimestamp() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formatter.format(new Date()); // 格式化为字符串如"2023-04-01 15:30:00"
}
}
```
要在控制器或其他服务类中使用这些方法,你可以注入`TimestampExample`实例并直接调用相应的方法。
springboot时间戳
在Spring Boot中获取当前时间戳可以使用Java 8的LocalDateTime类,示例代码如下:
```java
import java.time.LocalDateTime;
import java.time.ZoneOffset;
public class TimestampExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
long timestamp = now.toEpochSecond(ZoneOffset.of("+8"));
System.out.println(timestamp);
}
}
```
其中,toEpochSecond方法将LocalDateTime对象转换为秒级时间戳,ZoneOffset.of("+8")指定了时区为东八区(北京时间)。
阅读全文
相关推荐














