java中的System.currentTimeMillis()是什么?时间的单位转换以及方法的使用

在开发过程中,通常很多人都习惯使用new Date()来获取当前时间。new Date()所做的事情其实就是调用了System.currentTimeMillis()。如果仅仅是需要或者毫秒数,那么完全可以使用System.currentTimeMillis()去代替new Date(),效率上会高一点。如果需要在同一个方法里面多次使用new Date(),通常性能就是这样一点一点地消耗掉,这里其实可以声明一个引用。
System.currentTimeMillis() 获得的是自1970-1-01 00:00:00.000 到当前时刻的时间距离,类型为long。

下面是使用该方法的一个小例子:

//获得系统的时间,单位为毫秒,转换为妙
long totalMilliSeconds = System.currentTimeMillis();
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");


该方法较为常见的几个用法有:
1. 计算某任务 耗费的毫秒

long start = System.currentTimeMillis();
for (int i = 0; i < 5; i++) {
    Thread.sleep(10);
}
long end = System.currentTimeMillis();
System.out.println("for循环耗时" + (end - start) + "毫秒");

2.获得当前的系统时间

Date nowTime = new Date(System.currentTimeMillis());
SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd");
String now = sdFormatter.format(nowTime);
System.out.println(now);// 时间的输出

3.用当前毫秒数给文件命名等

File f = new File("c:\\"+System.currentTimeMillis() + "");
f.createNewFile();

4.其他用途,比如随机数的种子数等

本文转自 https://blog.csdn.net/qq_37370132/article/details/107905587,如有侵权,请联系删除。

posted @ 2022-09-19 11:03  yassine  阅读(1028)  评论(0编辑  收藏  举报