当前位置: 移动互联网学院 > Java培训 > JAVA开发 > Java获取当前时间戳的方法有哪些
Java获取当前时间戳的方法有哪些 时间:2017-08-22     来源:华清远见JAVA学院

时间戳就是一种类型,只是精度很高,比datetime要精确的多,通常用来防止数据出现脏读现象。那么Java中如何获得时间戳,Java获得当前时间戳的方法有哪些呢?

Java获取当前时间戳的三种方法

//方法 一

System.currentTimeMillis();

//方法 二

Calendar.getInstance().getTimeInMillis();

//方法 三

new Date().getTime();

Java获取当前时间的方法

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

String date = df.format(new Date());// new Date()为获取当前系统时间,也可使用当前时间戳

Java获取时间戳三种方法执行效率比较

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

long currentTime=System.currentTimeMillis();

}}

public static void testCalander(long times){//use 6299

for(int i=0;i

long currentTime=Calendar.getInstance().getTimeInMillis();

}}

public static void testDate(long times){

for(int i=0;i

long currentTime=new Date().getTime();

}}}

通过运行以上程序可以看出,Calendar.getInstance().getTimeInMillis() 这种方式速度慢,这是因为Canlendar要处理时区问题会耗费较多的时间。

以上给出了三种Java获取当前时间戳的方法,并给出了一个实例,说明哪一种方式速度更慢。

X