如何使用 java 计算两个日期之间的时差?

How to calculate the difference between two dates in hours with java?

我必须计算两个日期之间的差异,其中一个来自用户输入,另一个是当前时间。这是我目前所拥有的:

long time2 = System.currentTimeMillis();
System.out.print("Enter Time-in(hh:mm)");
String start = input.next();
String newTime[] = start.split(":");
String h = newTime[0];
String m = newTime[1];
String s = newTime[2];

int newH = Integer.parseInt(h);
int newM = Integer.parseInt(m);

LocalTime time1 = LocalTime.now();
long hr=ChronoUnit.HOURS.between(time1,time2);
System.out.println("Total number of hours: " + hr);

试试这个:

    System.out.print("Enter Time-in(hh:mm)");
    String start=input.next(); //make sure it have "hh:mm" format
    LocalTime userTime = LocalTime.parse(start);
    LocalTime currentTime = LocalTime.now();


    long diff = ChronoUnit.HOURS.between(currentTime, userTime);