简体   繁体   English

如何使用Java计算以小时为单位的两个日期之间的差异?

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

I have to calculate the difference bettween two dates where is one from the user`s input and the other is the current time. 我算算bettween两个日期 ,其中一个是从user`s输入,另一个是当前的时间 Here is what I have so far: 这是我到目前为止的内容:

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);

Try This : 尝试这个 :

    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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM