欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

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

来源: javaer 分享于  点击 9281 次 点评:184

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


目录
  • 方法1:使用System.currentTimeMillis()
  • 方法2:使用java.util.Date
  • 方法3:使用java.time.Instant
  • 方法4:使用java.time.LocalDateTime和java.time.ZoneId
  • 方法5:使用java.sql.Timestamp
  • 附:实例
  • 总结

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

方法1:使用System.currentTimeMillis()

long currentTimeMillis = System.currentTimeMillis();

方法2:使用java.util.Date

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

方法3:使用java.time.Instant

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

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

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

方法5:使用java.sql.Timestamp

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

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

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

附:实例

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<times;i++){
            long currentTime=System.currentTimeMillis();
        }
    }
 
    public static void testCalander(long times){//use 6299
        for(int i=0;i<times;i++){
            long currentTime=Calendar.getInstance().getTimeInMillis();
        }
    }
 
    public static void testDate(long times){
        for(int i=0;i<times;i++){
            long currentTime=new Date().getTime();
        }
    }
 
}

总结

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

您可能感兴趣的文章:
  • 教你使用Java获取当前时间戳的详细代码
  • java获取当前时间戳的方法
  • Java获取当前时间的时间戳(13位和10位)
  • Java获取当前时间戳案例详解
相关栏目:

用户点评