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(),通常性能就是這樣一點一點地消耗掉,這裏其實可以聲明一個引用。

複製代碼

        //獲得系統的時間,單位爲毫秒,轉換爲妙
        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");

複製代碼

小例子:

複製代碼

package demo.spli;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;


public class ShowCurrentTime {

    /**
     * @顯示當前時間
     * @2014.9.3
     */
    public static void main(String[] args) {
        // 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);
    }

}

複製代碼

System.currentTimeMillis()+3600*1000)可以這樣解讀:System.currentTimeMillis()相當於是毫秒爲單位,但是,後頭成了1000,就變成了以秒爲單位。那麼,3600秒=1小時,所以輸出爲當前時間的1小時後。

我們可以這樣控制時間:System.currentTimeMillis()+time*1000),裏面傳入的time是以秒爲單位,當傳入60,則輸出:當前時間的一分鐘後

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章