Java中计时

导读:本篇文章讲解 Java中计时,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

学习笔记··持续更新中

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://www.bmabk.com/index.php/post/91163.html

(0)
小半的头像小半

相关推荐

半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!