Java-获取当前时间的时间戳

获取当前时间戳的方法有很多种,可以根据你的需求和使用的Java版本来选择适合的方法。以下是五种获取当前时间戳的方法:

方法1:使用System.currentTimeMillis()

java 复制代码
long currentTimeMillis = System.currentTimeMillis();

方法2:使用java.util.Date

java 复制代码
Date currentDate = new Date();
long timestamp = currentDate.getTime();

方法3:使用java.time.Instant

java 复制代码
Instant currentInstant = Instant.now();
long timestamp = currentInstant.toEpochMilli();

方法4:使用java.time.LocalDateTime和java.time.ZoneId

java 复制代码
LocalDateTime localDateTime = LocalDateTime.now();
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
long currentTimestamp = zonedDateTime.toInstant().toEpochMilli();

方法5:使用java.sql.Timestamp

java 复制代码
Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
long timestamp = currentTimestamp.getTime();

根据你的具体需求,选择其中一种方法即可获取当前时间的时间戳。

最常用的是方法1 System.currentTimeMillis()

相关推荐
Vallelonga21 小时前
Rust 中的数组和数组切片引用
开发语言·rust
Kiri霧21 小时前
Rust模式匹配详解
开发语言·windows·rust
white-persist21 小时前
Python实例方法与Python类的构造方法全解析
开发语言·前端·python·原型模式
千里马-horse21 小时前
Async++ 源码分析8--partitioner.h
开发语言·c++·async++·partitioner
Java 码农1 天前
Centos7 maven 安装
java·python·centos·maven
harmful_sheep1 天前
maven mvn 安装自定义 jar 包
java·maven·jar
Lucis__1 天前
再探类&对象——C++入门进阶
开发语言·c++
007php0071 天前
某大厂跳动面试:计算机网络相关问题解析与总结
java·开发语言·学习·计算机网络·mysql·面试·职场和发展
JH30731 天前
第七篇:Buffer Pool 与 InnoDB 其他组件的协作
java·数据库·mysql·oracle
lsx2024061 天前
HTML 字符集
开发语言