import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.Instant;
public class LocalDateTimeToTimestamp {
public static void main(String[] args) {
// 创建一个 LocalDateTime 对象,表示当前日期和时间
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("LocalDateTime: " + localDateTime);
// 将 LocalDateTime 转换为 Instant
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
System.out.println("Instant: " + instant);
// 获取时间戳(以秒为单位)
long timestamp = instant.getEpochSecond();
System.out.println("Timestamp in seconds: " + timestamp);
// 获取时间戳(以毫秒为单位)
long timestampInMillis = instant.toEpochMilli();
System.out.println("Timestamp in milliseconds: " + timestampInMillis);
}
}
LocalDateTime
对象:使用 LocalDateTime.now()
获取当前的日期和时间。Instant
:通过 localDateTime.atZone(ZoneId.systemDefault()).toInstant()
将 LocalDateTime
转换为 Instant
。这里使用了系统默认的时区 (ZoneId.systemDefault()
)。instant.getEpochSecond()
获取以秒为单位的时间戳。instant.toEpochMilli()
获取以毫秒为单位的时间戳。这样就可以将 LocalDateTime
转换为时间戳了。
上一篇:java 判断文件夹是否存在
下一篇:java中的多态
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站