IT俱乐部 Java Java获取当前时间的时间戳方法总结

Java获取当前时间的时间戳方法总结

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

方法1:使用System.currentTimeMillis()

1
long currentTimeMillis = System.currentTimeMillis();

方法2:使用java.util.Date

1
2
Date currentDate = new Date();
long timestamp = currentDate.getTime();

方法3:使用java.time.Instant

1
2
Instant currentInstant = Instant.now();
long timestamp = currentInstant.toEpochMilli();

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

1
2
3
4
LocalDateTime localDateTime = LocalDateTime.now();
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
long currentTimestamp = zonedDateTime.toInstant().toEpochMilli();

方法5:使用java.sql.Timestamp

1
2
Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
long timestamp = currentTimestamp.getTime();

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

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

附:实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.Calendar;
import java.util.Date;
  
public class TimeTest {
    private static long _TEN_THOUSAND=10000;
    public static void main(String[] args) {
        long times=1000*_TEN_THOUSAND;
        long t1=System.currentTimeMillis();
        testSystem(times);
        long t2=System.currentTimeMillis();
        System.out.println(t2-t1);
  
        testCalander(times);
        long t3=System.currentTimeMillis();
        System.out.println(t3-t2);
  
        testDate(times);
        long t4=System.currentTimeMillis();
        System.out.println(t4-t3);
    }
  
    public static void testSystem(long times){//use 188
        for(int i=0;i

总结

到此这篇关于Java获取当前时间的时间戳的文章就介绍到这了,更多相关Java获取当前时间时间戳内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/java/11783.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部