我試圖獲得兩個時間值之間的時間差。 (11:00:00和12:43:00)上面的輸入顯示正確的輸出。兩次使用java之間的時間差
**
Time in seconds: 6180 seconds.
Time in minutes: 103 minutes.
Time in hours: 1 hours.
Time in hours Round : 2 hours.
** 輸入值( 「11:00:00」 和 「2點43分00秒」),它應該給我們3小時圓形值 **
Time in seconds: -29820 seconds.
Time in minutes: -497 minutes.
Time in hours: -8 hours.
Time in hours Round : -8 hours.
**
import java.lang.Math;
import java.text.SimpleDateFormat;
import java.util.Date;
public class HelloWorld
{
public static void main(String[] args)
{
String dateStart = "11:00:00";
String dateStop = "12:43:00";
// Custom date format
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (Exception e) {
e.printStackTrace();
}
// Get msec from each, and subtract.
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff/1000;
long diffMinutes = diff/(60 * 1000);
long diffHours = diff/(60 * 60 * 1000);
int parkingEntry=2;
int firstHour=3;
int parkingRate=4;
int Total=0;
System.out.println("Time in seconds: " + diffSeconds + " seconds.");
System.out.println("Time in minutes: " + diffMinutes + " minutes.");
System.out.println("Time in hours: " + diffHours + " hours.");
double my_hrs=diffMinutes/60d;
int r = (int) Math.round(my_hrs);
System.out.println("Time in hours Round : " + r + " hours.");
}
}
嘗試使用長diffInMillis = d2.getTimeInMillis() - d1.getTimeInMillis() –
嘗試使用['Duration']( https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html)和['LocalTime'](https://docs.oracle.com/javase/8/docs/api /java/time/LocalTime.html) – MadProgrammer
@ user7790438,這將不會編譯(如果它確實,將不會幫助提問者的問題)。你在'Calendar'類中的方法令人困惑。 「日期」和「日曆」之間的不一致只是當您更改爲「本地時間」和「持續時間」(如MadProgrammer建議的)時很大程度上克服的一個問題。 –