我正在尝试获取两个时间值之间的时间差。 (11:00:00 和 12:43:00)对于上述输入,它显示正确的输出。
**
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.");
}
}
最佳答案
格式“HH:mm:ss”是 24 小时格式。因此,当您检查“11:00:00”和“2:43:00”之间的时差时,您实际上是在检查上午 11 点和凌晨 2:43 之间的时差。
将您的输入更改为“11:00:00”和“14:43:00”。
关于java - 使用java的两个时间之间的时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43581079/