Java, how do I get the difference in seconds between 2 dates?

2個 java 的日期物件, 如何取得相差的秒數.

解法:
https://stackoverflow.com/questions/1970239/in-java-how-do-i-get-the-difference-in-seconds-between-2-dates

If you have two Dates you can call getTime on them to get millseconds, get the diff and divide by 1000. For example

Date d1 = ...;
Date d2 = ...;
long seconds = (d2.getTime()-d1.getTime())/1000;

To get pretty timing differences:
https://stackoverflow.com/questions/4927856/how-can-i-calculate-a-time-difference-in-java

// d1, d2 are dates
long diff = d2.getTime() - d1.getTime();

long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);

System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *