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()

相关推荐
lly2024061 分钟前
AJAX PHP 实践指南
开发语言
Never_Satisfied4 分钟前
在JavaScript / HTML中,cloneNode()方法详细指南
开发语言·javascript·html
曹轲恒5 分钟前
SpringBoot的热部署
java·spring boot·后端
huwei8536 分钟前
python设计通用表格类 带右键菜单
开发语言·windows·python
Remember_9938 分钟前
深入理解 Java String 类:从基础原理到高级应用
java·开发语言·spring·spring cloud·eclipse·tomcat
—Qeyser10 分钟前
Flutter组件 - BottomNavigationBar 底部导航栏
开发语言·javascript·flutter
666HZ66613 分钟前
数据结构3.0 栈、队列和数组
开发语言·数据结构·算法
bing.shao13 分钟前
Golang 在OPC领域的应用
开发语言·后端·golang
程序员侠客行22 分钟前
Mybatis插件原理及分页插件
java·后端·架构·mybatis
a努力。23 分钟前
得物Java面试被问:Netty的ByteBuf引用计数和内存释放
java·开发语言·分布式·python·面试·职场和发展