System.currentTimeMillis()计算方式与时间的单位转换详解
一、时间的单位转换
1秒=1000毫秒(ms) 1毫秒=1/1,000秒(s)
1秒=1,000,000 微秒(μs) 1微秒=1/1,000,000秒(s)
1秒=1,000,000,000 纳秒(ns) 1纳秒=1/1,000,000,000秒(s)
1秒=1,000,000,000,000 皮秒(ps) 1皮秒=1/1,000,000,000,000秒(s)
1分钟=60秒
1小时=60分钟=3600秒
二、System.currentTimeMillis()计算方式
在开发过程中,通常很多人都习惯使用new Date()来获取当前时间。new Date()所做的事情其实就是调用了System.currentTimeMillis()。如果仅仅是需要或者毫秒数,那么完全可以使用System.currentTimeMillis()去代替new Date(),效率上会高一点。如果需要在同一个方法里面多次使用new Date(),通常性能就是这样一点一点地消耗掉,这里其实可以声明一个引用。
//获得系统的时间,单位为毫秒,转换为妙
longtotalMilliSeconds=System.currentTimeMillis();
longtotalSeconds=totalMilliSeconds/1000;
//求出现在的秒
longcurrentSecond=totalSeconds%60;
//求出现在的分
longtotalMinutes=totalSeconds/60;
longcurrentMinute=totalMinutes%60;
//求出现在的小时
longtotalHour=totalMinutes/60;
longcurrentHour=totalHour%24;
//显示时间
System.out.println("总毫秒为:"+totalMilliSeconds);
System.out.println(currentHour+":"+currentMinute+":"+currentSecond+"GMT");
小例子:
packagedemo.spli;
importjava.text.DateFormat;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.TimeZone;
publicclassShowCurrentTime{
/**
*@显示当前时间
*@2014.9.3
*/
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
//获得系统的时间,单位为毫秒,转换为妙
longtotalMilliSeconds=System.currentTimeMillis();
DateFormatdateFormatterChina=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM);//格式化输出
TimeZonetimeZoneChina=TimeZone.getTimeZone("Asia/Shanghai");//获取时区这句加上,很关键。
dateFormatterChina.setTimeZone(timeZoneChina);//设置系统时区
longtotalSeconds=totalMilliSeconds/1000;
//求出现在的秒
longcurrentSecond=totalSeconds%60;
//求出现在的分
longtotalMinutes=totalSeconds/60;
longcurrentMinute=totalMinutes%60;
//求出现在的小时
longtotalHour=totalMinutes/60;
longcurrentHour=totalHour%24;
//显示时间
System.out.println("总毫秒为:"+totalMilliSeconds);
System.out.println(currentHour+":"+currentMinute+":"+currentSecond+"GMT");
DatenowTime=newDate(System.currentTimeMillis());
System.out.println(System.currentTimeMillis());
SimpleDateFormatsdFormatter=newSimpleDateFormat("yyyy-MM-ddHH:mm:dd");
StringretStrFormatNowDate=sdFormatter.format(nowTime);
System.out.println(retStrFormatNowDate);
}
}
System.currentTimeMillis()+3600*1000)可以这样解读:System.currentTimeMillis()相当于是毫秒为单位,但是,后头成了1000,就变成了以秒为单位。那么,3600秒=1小时,所以输出为当前时间的1小时后。
我们可以这样控制时间:System.currentTimeMillis()+time*1000),里面传入的time是以秒为单位,当传入60,则输出:当前时间的一分钟后
到此这篇关于System.currentTimeMillis()计算方式与时间的单位转换详解的文章就介绍到这了,更多相关System.currentTimeMillis()计算方式与时间单位内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!