获取当前时间戳的方法有很多种,可以根据你的需求和使用的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
总结
到此这篇关于Java获取当前时间的时间戳的文章就介绍到这了,更多相关Java获取当前时间时间戳内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!
