方法一:System.currentTimeMillis();
方法二:Calendar.getInstance().getTimeInMillis();
方法三:new Date().getTime();
@RequestMapping(value = {"/test"})
public void test() throws Exception{
long _TEN_THOUSAND=500;
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){
for(int i=0;i<times;i++){
long currentTime=System.currentTimeMillis();
}
}
public static void testCalander(long times){
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();
}
}
从代码中我们可以看到我循环50万次所耗用的时间相比较,得出来的数据如下:
System.currentTimeMillis()执行50万次所耗用时间:7毫秒
Calendar.getInstance().getTimeInMillis()执行50万次所耗用时间:327毫秒
new Date().getTime()执行50万次所耗用时间:10毫秒
相信看到上述性能对比,在低频状态时System.currentTimeMillis和new Date()在性能上几乎可以忽略,性能不相上下。
使用System.currentTimeMillis我们应该怎么进行转换呢?
我们将结果打印一下:
使用System.currentTimeMillis打印出来的时间戳:1593654870403;
使用new Date()打印出来的时间戳:Thu Jul 02 09:54:30 CST 2020;
从结果可以看到时间戳格式上很多时候并非是想要的,那么我们接下来对System.currentTimeMillis时间戳进行转换
/**
* @显示当前时间
* @2014.9.3
*/
public void time() throws Exception{
// TODO Auto-generated method stub
//获得系统的时间,单位为毫秒,转换为妙
long totalMilliSeconds = System.currentTimeMillis();
DateFormat dateFormatterChina = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM);//格式化输出
TimeZone timeZoneChina = TimeZone.getTimeZone("Asia/Shanghai");//获取时区 这句加上,很关键。
dateFormatterChina.setTimeZone(timeZoneChina);//设置系统时区
long totalSeconds = totalMilliSeconds / 1000;
//求出现在的秒
long currentSecond = totalSeconds % 60;
//求出现在的分
long totalMinutes = totalSeconds / 60;
long currentMinute = totalMinutes % 60;
//求出现在的小时
long totalHour = totalMinutes / 60;
long currentHour = totalHour % 24;
//显示时间
System.out.println("总毫秒为: " + totalMilliSeconds);
System.out.println(currentHour + ":" + currentMinute + ":" + currentSecond + " GMT");
Date nowTime = new Date(System.currentTimeMillis());
System.out.println(System.currentTimeMillis());
SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
String retStrFormatNowDate = sdFormatter.format(nowTime);
System.out.println(retStrFormatNowDate);
}
那么最后我们就可以获得转换后的时间值。
本文地址:https://blog.csdn.net/gumindong/article/details/107068782
如对本文有疑问, 点击进行留言回复!!
Postgresql结合postgis使用java的JDBC连接
网友评论