java中的时间戳是毫秒为单位,13位;unix的时间戳是秒,10位
一、java中获取时间戳
//方法 一
System.currentTimeMillis();
//方法 二
Calendar.getInstance().getTimeInMillis();
//方法 三
new Date().getTime();
三种方法性能比较:
每种方法运行1亿次
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimeStamp {
private long count = 10000*10000;
public static void main(String[] args){
TimeStamp timeStamp = new TimeStamp();
System.out.println(System.currentTimeMillis());
System.out.println(Calendar.getInstance().getTimeInMillis());
System.out.println(new Date().getTime());
System.out.println("==============================");
long t1= System.currentTimeMillis();
timeStamp.test1();
long t2 = System.currentTimeMillis();
System.out.println(t2-t1);
timeStamp.test2();
long t3 = System.currentTimeMillis();
System.out.println(t3-t2);
timeStamp.test3();
long t4 = System.currentTimeMillis();
System.out.println(t4-t3);
System.out.println("=======================");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
System.out.println(format.format(new Date()));
}
public void test1() {
for (int i = 0; i < count; i++) {
long current = System.currentTimeMillis();//1349
}
}
public void test2() {
for (int i = 0; i < count; i++) {
long current = Calendar.getInstance().getTimeInMillis();//21224
}
}
public void test3(){
for(int i = 0;i
long current = new Date().getTime();//1353
}
}
}
结果如下:
1499262134642
1499262134651
1499262134676
==============================
1349
21224
1353
=======================
2017-07-05 09:07:38
结果发现 System.currentTimeMillis() 这种方式速度最快
Calendar.getInstance().getTimeInMillis() 这种方式速度最慢,看看源码会发现,Canlendar因为要处理时区问题会耗费很多的时间。
所以建议多使用第一种方式。
二、java中获取当前时间
//方法一
Calendar.getInstance().getTime()
//方法二
new Date()
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateTest {
public static void main(String[] args) throws ParseException {
Calendar now = Calendar.getInstance();
System.out.println("年: " + now.get(Calendar.YEAR));
System.out.println("月: " + (now.get(Calendar.MONTH) + 1) + "");
System.out.println("日: " + now.get(Calendar.DAY_OF_MONTH));
System.out.println("时: " + now.get(Calendar.HOUR_OF_DAY));
System.out.println("分: " + now.get(Calendar.MINUTE));
System.out.println("秒: " + now.get(Calendar.SECOND));
System.out.println("当前时间毫秒数:" + now.getTimeInMillis());
System.out.println(now.getTime());
Date d = new Date();
System.out.println(d);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateNowStr = sdf.format(d);
System.out.println("格式化后的日期:" + dateNowStr);
String str = "2012-1-13 17:26:33"; //要跟上面sdf定义的格式一样
Date today = sdf.parse(str);
System.out.println("字符串转成日期:" + today);
}
}
输出结果:
年: 2017
月: 7
日: 5
时: 23
分: 52
秒: 33
当前时间毫秒数:1499269953267
Wed Jul 05 23:52:33 CST 2017
Wed Jul 05 23:52:33 CST 2017
格式化后的日期:2017-07-05 23:52:33
字符串转成日期:Fri Jan 13 17:26:33 CST 2012