Java TimeUnit:時間單位轉換與時間日期間隔計算

若你要找的是時間的格式化輸出輸入的話,
請見:Java:日期時間格式處理:Date、Calendar、DateFormat、SimpleDateFormat

如果大家對 Java 的時間有基本了解的話,
就會知道 Java 對時間的處理是用一個 long 值,
這個 long 值代表的是自 1970 年 1 月 1 日 00:00:00 GMT 至該時間的毫秒數

因為這個計算方式,所以我們在轉換時間單位時常常需要自己作乘除運算,
例如把毫秒數除以1000轉成秒,再除以60轉成分,再除以60轉成小時,
針對不同的單位需要自己產生一個常數來轉換,雖然不難但很麻煩。


因應這一點,Java 在 1.5, 1.6 的版本之後,
在 java.util.concurrent.TimeUnit 內新增了許多轉換的 method:
Modifier and TypeMethod and Description
longconvert(long sourceDuration, TimeUnit sourceUnit)
Convert the given time duration in the given unit to this unit.
voidsleep(long timeout)
Performs a Thread.sleep using this time unit.
voidtimedJoin(Thread thread, long timeout)
Performs a timed Thread.join using this time unit.
voidtimedWait(Object obj, long timeout)
Performs a timed Object.wait using this time unit.
longtoDays(long duration)
Equivalent to DAYS.convert(duration, this).
longtoHours(long duration)
Equivalent to HOURS.convert(duration, this).
longtoMicros(long duration)
Equivalent to MICROSECONDS.convert(duration, this).
longtoMillis(long duration)
Equivalent to MILLISECONDS.convert(duration, this).
longtoMinutes(long duration)
Equivalent to MINUTES.convert(duration, this).
longtoNanos(long duration)
Equivalent to NANOSECONDS.convert(duration, this).
longtoSeconds(long duration)
Equivalent to SECONDS.convert(duration, this).
static TimeUnitvalueOf(String name)
Returns the enum constant of this type with the specified name.
static TimeUnit[]values()
Returns an array containing the constants of this enum type, in the order they are declared.
這個 TimeUnit 除了直接拿來用在時間的單位轉換外,也可能被其他的 method 拿來用,
例如 ScheduledExecutorService 中的 method:
ScheduledFuture  schedule(Runnable command, long delay, TimeUnit unit)。

在這篇中我們先簡單地示範時間單位轉換和時間日期間隔的計算,
之後若有時間再來做其他應用的介紹。

以下是程式碼:
 1 package werdna1222coldcodes.blogspot.com.demo.timeUnit;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 import java.util.concurrent.TimeUnit;
 7 
 8 public class TimeUnitDemo {
 9     
10     public static void main(String[] args) throws ParseException {
11 
12         TimeUnitDemo timeUnitDemo = new TimeUnitDemo();
13         timeUnitDemo.testUnitConvert();
14         timeUnitDemo.testTimeDuration();
15     }
16     
17     void testUnitConvert(){
18 
19         long seconds = 120;
20         long mins = TimeUnit.MINUTES.convert(seconds, TimeUnit.SECONDS)
21                     ;
22         System.out.println("Use TimeUnit.conver:");
23         System.out.println(seconds + " seconds equals to " + mins + " 
24                            mins.");
25         
26         mins = TimeUnit.SECONDS.toMinutes(seconds);
27         System.out.println("Use TimeUnit.toMinutes:");
28         System.out.println(seconds + " seconds equals to " + mins + " 
29                            mins.\n");
30     }
31     
32     void testTimeDuration() throws ParseException{
33 
34         //  準備輸入輸出的格式,如:2011/12/1
35         SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
36 
37         //  利用 SimpleDateFormat 來parse 日期的字串
38         Date beginDate = sdf.parse("2011/12/1");
39         Date endDate = sdf.parse("2012/1/9");
40         long days = TimeUnit.MILLISECONDS.toDays(endDate.getTime() - 
41                     beginDate.getTime());
42         
43         System.out.println("beginDate: " + sdf.format(beginDate));
44         System.out.println("endDate: " + sdf.format(endDate));
45         System.out.println("duration: " + days + " days");
46     }
47 }

輸出結果為:
Use TimeUnit.conver:
120 seconds equals to 2 mins.
Use TimeUnit.toMinutes:
120 seconds equals to 2 mins.

beginDate: 2011/12/01
endDate: 2012/01/09
duration: 39 days

由上面我們可以知道只要使用的 convert 這個 method,
就可以將任意時間單位的 long 值轉換為另一單位。
而使用 toMinutes, toDays 這類 toXXX 的 method,
一樣也可以成功轉換單位,因為其實這些 toXXX 背後會自己再呼叫 convert。

另外我們也看到時間間隔的計算可以直接將兩個 Date 物件,
呼叫 getTime 取得時間的 long值後直接相減,
然後就可以將這個毫秒的時間間隔轉換成我們想要的單位了。
使用起來是不是很簡單呢?

若想知道更多有關 Java 時間相關的轉換、排程、格式化輸出輸入等應用,請見:
Java 時間日期處理範例大全:含時間單位格式轉換、期間計算、排程等

關鍵字:Java, 時間, 相減, 加減, 計算, 轉換, 比較, 差, 毫秒

    這個網誌中的熱門文章

    【博客來折價券】博客來免費序號e-coupon分享(持續更新)

    【博客來折價券】25/50/100/150現領現折+天天簽到換200+OP兩倍換!

    【銀行代碼查詢】3碼銀行代碼列表、7碼分行代碼查詢

    【新光卡攻略】台灣Pay單筆888送50+寰宇3%,LINE會員繳費10%!

    【Hami Video】免費Hami Video體驗/試用序號分享(隨時更新)!

    Gmail 無限分身術:產生無限 email 帳號