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

相关推荐
WiChP7 小时前
【V0.1B5】从零开始的2D游戏引擎开发之路
java·服务器·数据库
cch89187 小时前
汇编与Java:底层与高层的编程对决
java·开发语言·汇编
荒川之神8 小时前
拉链表概念与基本设计
java·开发语言·数据库
cch89188 小时前
汇编与Go:底层到高层的编程差异
java·汇编·golang
chushiyunen8 小时前
python中的@Property和@Setter
java·开发语言·python
禾小西8 小时前
Java中使用正则表达式核心解析
java·python·正则表达式
yoyo_zzm8 小时前
JAVA (Springboot) i18n国际化语言配置
java·spring boot·python
小樱花的樱花8 小时前
C++ new和delete用法详解
linux·开发语言·c++
froginwe118 小时前
C 运算符
开发语言