一些簡單的code紀錄一下.
計算時間差的程式碼.
//import java.util.concurrent.TimeUnit
String dateStart = "11/03/14 09:29:58";
String dateStop = "11/03/14 09:33:43";
// Custom date format
SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (ParseException e) {
e.printStackTrace();
}
// Get msec from each, and subtract.
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (1000);
long diffHours = diff / (60 * 1000);
System.out.println("Time in seconds: " + diffSeconds + " seconds.");
System.out.println("Time in minutes: " + diffMinutes + " minutes.");
System.out.println("Time in hours: " + diffHours + " hours.");
//You can also try this function.
//long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
//long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
執行後輸出格式如下
Time in seconds: 45 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.