Search code examples
javatimejava-timetimedeltalocaltime

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

Solution

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