java8日期怎么获取时间戳
时间: 2023-07-11 20:57:14 浏览: 68
在Java 8中,可以使用`Instant`类来获取当前时间的时间戳。以下是一个示例代码:
```java
Instant timestamp = Instant.now();
System.out.println(timestamp.getEpochSecond()); // 输出当前时间戳,单位为秒
System.out.println(timestamp.toEpochMilli()); // 输出当前时间戳,单位为毫秒
```
其中,`getEpochSecond()`方法返回当前时间的时间戳,单位为秒;而`toEpochMilli()`方法返回当前时间的时间戳,单位为毫秒。
相关问题
java 获取时间戳方式
在Java中获取时间戳可以使用以下两种方式:
1. 使用System类的currentTimeMillis()方法获取当前时间戳,返回当前时间与1970年1月1日00:00:00之间以毫秒为单位的时间差。
```java
long timestamp = System.currentTimeMillis();
```
2. 使用Java 8中的Instant类获取当前时间戳,返回当前时间与1970年1月1日00:00:00之间以纳秒为单位的时间差。
```java
Instant instant = Instant.now();
long timestamp = instant.toEpochMilli();
```
java获取指定日期的时间戳
在Java中获取指定日期的时间戳可以使用java.time包中的LocalDateTime类和Instant类。
首先,需要创建一个LocalDateTime对象,表示指定日期和时间。可以使用LocalDateTime.of()方法创建一个包含年、月、日、小时、分钟和秒的LocalDateTime对象。例如:
LocalDateTime dateTime = LocalDateTime.of(2022, 6, 30, 23, 59, 59);
接下来,需要将这个LocalDateTime对象转换为时间戳。可以使用toEpochSecond()方法将LocalDateTime对象转换为从1970年1月1日00:00:00开始的秒数。例如:
long second = dateTime.toEpochSecond(ZoneOffset.of("+8"));
但是这里的toEpochSecond()方法只能获取到秒级别的时间戳,如果需要获取毫秒级别的时间戳,则需要将秒数乘以1000。例如:
long millisecond = dateTime.toEpochSecond(ZoneOffset.of("+8")) * 1000;
同时,在转换为时间戳时需要注意时区。toEpochSecond()方法需要一个ZoneOffset对象作为参数,该对象表示时区的偏移量。ZoneOffset.UTC表示世界标准时间,ZoneOffset.of("+8")表示东八区。
最后,可以将时间戳转换为字符串输出。例如:
String timestamp = String.valueOf(millisecond);
System.out.println("指定日期的时间戳为:" + timestamp);
综上所述,通过LocalDateTime类和Instant类即可轻松获取指定日期的时间戳。