如果你只是想獲得日期之間的日子裏,你可以使用類似:
public static void main(String[] args) {
long initial = getTime("20-jul-2015 11:09:25"); /*you use System.currentTimeMillis() at the beginning*/
long finalTime = getTime("21-jul-2016 15:21:26"); /*you use System.currentTimeMillis() at the capture of final time.*/
printElapsedTime(initial, finalTime);
}
private static void printElapsedTime(long initial, long finalTime) {
long lapse = finalTime - initial;
long secs = (lapse/(1000))%60;
long mins = lapse/(1000*60)%60;
long hrs = lapse/(1000*60*60)%24;
long days = lapse/(1000*60*60*24);
StringBuilder lapseMsg = new StringBuilder("Elapsed time since ").append(new Date(initial)).append(" to " + new Date(finalTime)).append(":\r\n");
lapseMsg.append(days).append(" Days, ").append(hrs).append(" Hours, ").append(mins).append(" Minutes, ").append(secs).append(" seconds");
System.out.println(lapseMsg.toString());
}
/*just used to get any date to test.*/
private static long getTime(String date) {
DateFormat format = DateFormat.getDateTimeInstance();
try {
return format.parse(date).getTime();
} catch (ParseException e) {
throw new RuntimeException();
}
}
,如果你需要的東西更像是一個你可以使用日曆逝去的幾個月,做一些修正,以複雜的@ OldCurmudgeon解決方案。 (它並不適用於我的方式)
更容易與時期(可在Java 1.8) - [鏈接](https://docs.oracle.com/javase/8/docs/api/java/ time/Period.html) –
我們是24小時直線對話嗎?或者您是否需要考慮由[夏令時](http://stackoverflow.com/tags/dst/info)轉換創建的缺失時間間隔和重複時間重疊? –