-1

I want to calculate the time difference hour and minute without using java dateformat

user should input like Clock In: 23:00 Clock Out: 01:00

The expected output shall be something like 2 hours 00 minutes.

But how can I calculate them?

Scanner input = new Scanner(System.in);

    //Read data
    System.out.print("Clock In: ");
    String sTimeIn = input.nextLine();

    System.out.print("Clock Out: ");
    String sTimeOut = input.nextLine();

    // Process data
    String sHourIn = sTimeIn.substring(0, 2);
    String sMinuteIn = sTimeIn.substring(3, 5);
    String sHourOut = sTimeOut.substring(0, 2);
    String sMinuteOut = sTimeOut.substring(3, 5);

    int iHourIn = Integer.parseInt(sHourIn);
    int iMinuteIn = Integer.parseInt(sMinuteIn);
    int iHourOut = Integer.parseInt(sHourOut);
    int iMinuteOut = Integer.parseInt(sMinuteOut);

    int sumHour =
    int sumMinute = 

    //Display Output
    System.out.print(sumHour +"Hour "+ sumMinute + " Minute");

}

}

After I have reviewed all the solutions you given. Here is what I have edited. But I still found an issue is, if Clock in 23:00 Clock Out: 01:00 and the output is 22Hour(s) 0 Minute(s). The output should be 02 Hour(s) 0 Minute(s).

System.out.println("*Your time format must be 00:00");
        System.out.print("Clock In: ");
        String getTimeIn = input.nextLine();

        System.out.print("Clock Out: ");
        String getTimeOut = input.nextLine();

        // Process data
        String sHourIn = getTimeIn.substring(0, 2);
        String sMinuteIn = getTimeIn.substring(3, 5);
        String sHourOut = getTimeOut.substring(0, 2);
        String sMinuteOut = getTimeOut.substring(3, 5);

        int sumHour = Integer.parseInt(sHourIn) - Integer.parseInt(sHourOut);
        int sumMinute = Integer.parseInt(sMinuteIn) - Integer.parseInt(sMinuteOut);

        if(sumHour < 0) {
            sumHour =-sumHour;
        }

        if(sumMinute < 0) {
            sumMinute =- sumMinute;
        }

        //Display Output
         System.out.print(sumHour +"Hour(s) "+ sumMinute + " Minute(s)");
gary
  • 21
  • 7
  • https://stackoverflow.com/questions/4927856/how-to-calculate-time-difference-in-java – Jens Jan 16 '19 at 10:14
  • 1
    there are methods provided by Java to get data like that in the Time api, why don't you use those? – Stultuske Jan 16 '19 at 10:14
  • @Jens I have mentioned "without using dateformat" – gary Jan 16 '19 at 10:19
  • @GaryHooi I haven't mentioned dateformat. – Stultuske Jan 16 '19 at 10:21
  • @Stultuske I have mentioned "without using dateformat" – gary Jan 16 '19 at 10:22
  • 1
    @GaryHooi yes, I've seen that. but since I never said anything about using dateformat, or whatever you are talking about, I don't see your point. – Stultuske Jan 16 '19 at 10:23
  • There are 24 hours in a day and 60 minutes in an hour, what is your issue because to me the math looks pretty straightforward? And the answer to your example is 21 hours and 50 minutes, not 2 hours and 10 minutes. – Joakim Danielson Jan 16 '19 at 10:28
  • @JoakimDanielson unless he mixed up the clocked in and clocked out times – Stultuske Jan 16 '19 at 10:31
  • My advice: convert both times to "minutes past midnight" and subtract "out" - "in". If it's < 0 then (I assume) they're clocking out on the following day so add 1 day's worth of minutes. Then convert back to hours and minutes if needed. – Peter Hull Jan 16 '19 at 10:43
  • @OleV.V. You should link to one that doesn't use any date formatter class, old or new, since that is part of the requirement. Otherwise this is not a duplicate. – Joakim Danielson Jan 16 '19 at 21:13
  • Thanks, @JoakimDanielson, I missed those four words (even though two of them were in boldface). I have reopened. Gary Hooi, why without date format? While the `DateFormat` class is notoriously troublesome and long outdated, the `LocalTime` class can parse your times without a formatter, wouldn’t that be ideal? – Ole V.V. Jan 16 '19 at 21:33
  • Possible duplicate of [How to avoid negative time between time difference?](https://stackoverflow.com/questions/44387638/how-to-avoid-negative-time-between-time-difference) Of the four answers, none uses `DateFormat`. – Ole V.V. Jan 17 '19 at 13:26

5 Answers5

2

As @Stultuske said the time library should be a safer option, I have provided an example below

import java.time.LocalTime;

public class HelloWorld
{
  public static void main(String[] args)
  {
      LocalTime in = LocalTime.parse("18:20");
      LocalTime out = LocalTime.parse("20:30");

      int hoursDiff = (out.getHour() - in.getHour()),
          minsDiff  = (int)Math.abs(out.getMinute() - in.getMinute()),
          secsDiff  = (int)Math.abs(out.getSecond() - in.getSecond());

      System.out.println(hoursDiff+":"+minsDiff+":"+secsDiff);
  }
}

Update:

The solution is missing the midnight crossing as pointed by @Joakim Danielson, So I have modified the above solution to check for in > out or out < in.

import java.time.LocalTime;

public class HelloWorld
{
  public static void main(String[] args)
  {
      LocalTime in = LocalTime.parse("16:00");
      LocalTime out = LocalTime.parse("01:00");

      int hOut = out.getHour(),
          hIn  = in.getHour();

      int hoursDiff = hOut < hIn ? 24 - hIn + hOut : hOut - hIn,
          minsDiff  = (int)Math.abs(out.getMinute() - in.getMinute()),
          secsDiff  = (int)Math.abs(out.getSecond() - in.getSecond());

      System.out.println(hoursDiff+":"+minsDiff+":"+secsDiff);
  }
}
Bargros
  • 521
  • 6
  • 18
2

If you want to use LocalTime and ChronoUnit classes of Java 8:

String sTimeIn = "23:15";
String sTimeOut = "1:30";
LocalTime timeIn = LocalTime.parse(sTimeIn, DateTimeFormatter.ofPattern("H:m"));
LocalTime timeOut = LocalTime.parse(sTimeOut, DateTimeFormatter.ofPattern("H:m"));
long dif = ChronoUnit.MINUTES.between(timeIn, timeOut);
if (dif < 0)
    dif += 24 * 60;
long sumHour = dif / 60;
long sumMinute = dif % 60;

System.out.println(sumHour + ":"+ sumMinute);

or formatted to HH:mm:

System.out.println(String.format("%02d", sumHour) + ":"+ String.format("%02d", sumMinute));

will print:

02:15
forpas
  • 160,666
  • 10
  • 38
  • 76
1

Here is my suggested solution including some simple (not perfect) validation of the input, I have put the solution inside a method so asking user for input is not handled

public static void calcTime(String sTimeIn, String sTimeOut) {
    final String timePattern = "[0-2][0-9]:[0-5][0-9]";

    if (sTimeIn == null || sTimeOut == null || !sTimeIn.matches(timePattern) || !sTimeIn.matches(timePattern)) {
        throw new IllegalArgumentException();
    }

    String[] timeIn = sTimeIn.split(":");
    String[] timeOut = sTimeOut.split(":");

    int inMinutes = 60 * Integer.valueOf(timeIn[0]) + Integer.valueOf(timeIn[1]);
    int outMinutes = 60 * Integer.valueOf(timeOut[0]) + Integer.valueOf(timeOut[1]);

    int diff = 0;
    if (outMinutes > inMinutes) {
        diff = outMinutes - inMinutes;
    } else if (outMinutes < inMinutes) {
        diff = outMinutes + 24 * 60 - inMinutes;
    }

    System.out.printf("Time difference between %s and %s is %d hours and %d minutes\n", sTimeIn, sTimeOut, diff / 60, diff % 60);
}

Update
Here is a solution based on LocalTime and Duration

public static void calcTime2(String sTimeIn, String sTimeOut) {
    final String timePattern = "[0-2][0-9]:[0-5][0-9]";

    if (sTimeIn == null || sTimeOut == null || !sTimeIn.matches(timePattern) || !sTimeIn.matches(timePattern)) {
        throw new IllegalArgumentException();
    }

    String[] timeIn = sTimeIn.split(":");
    String[] timeOut = sTimeOut.split(":");

    LocalTime localTimeIn = LocalTime.of(Integer.valueOf(timeIn[0]), Integer.valueOf(timeIn[1]));
    LocalTime localTimeOut = LocalTime.of(Integer.valueOf(timeOut[0]), Integer.valueOf(timeOut[1]));

    Duration duration;
    if (localTimeOut.isAfter(localTimeIn)) {
        duration = Duration.between(localTimeIn, localTimeOut);
    } else {
        Duration prevDay = Duration.ofHours(24).minusHours(localTimeIn.getHour()).minusMinutes(localTimeIn.getMinute());
        Duration nextDay = Duration.between(LocalTime.MIDNIGHT, localTimeOut);
        duration = prevDay.plus(nextDay);
    }

    System.out.printf("Time difference between %s and %s is %d hours and %d minutes\n", sTimeIn, sTimeOut,
            duration.toHours(), duration.minusHours(duration.toHours()).toMinutes());     
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
0

try this :

public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
   //Read data
   System.out.println("Clock In: ");
   String sTimeIn = "20:30";

   System.out.println("Clock Out: ");
   String sTimeOut = "18:20";

   // Process data
   String sHourIn = sTimeIn.substring(0, 2);
   String sMinuteIn = sTimeIn.substring(3, 5);
   String sHourOut = sTimeOut.substring(0, 2);
   String sMinuteOut = sTimeOut.substring(3, 5);

   int iHourIn = Integer.parseInt(sHourIn);
   int iMinuteIn = Integer.parseInt(sMinuteIn);
   int iHourOut = Integer.parseInt(sHourOut);
   int iMinuteOut = Integer.parseInt(sMinuteOut);

   Calendar cal = Calendar.getInstance();

   cal.set(Calendar.HOUR_OF_DAY,iHourIn);
   cal.set(Calendar.MINUTE,iMinuteIn);
   cal.set(Calendar.SECOND,0);
   cal.set(Calendar.MILLISECOND,0);
   Long timeIn = cal.getTime().getTime();

   cal.set(Calendar.HOUR_OF_DAY,iHourOut);
   cal.set(Calendar.MINUTE,iMinuteOut);
   cal.set(Calendar.SECOND,0);
   cal.set(Calendar.MILLISECOND,0);
   Long timeOut = cal.getTime().getTime();

   Long finaltime=  timeIn-timeOut;

   // Convert the result to Hours and Minutes

   Long temp = null;
   // get hours
   temp = finaltime % 3600000 ;
   int sumHour = (int) ((finaltime - temp) / 3600000 );

   finaltime = temp;

   int sumMinute = (int) (finaltime/ 60000);

   //Display Output
   System.out.println(sumHour +" Hour "+ sumMinute + " Minute");
}   
juanlumn
  • 6,155
  • 2
  • 30
  • 39
-1

I have added some code in addition to your code. Please check and let me know if this is enough for your requirement

public class MainClass1 {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    //Read data
    System.out.print("Clock In: ");
    String[] sTimeIn = input.nextLine().split(":");

    System.out.print("Clock Out: ");
    String[] sTimeOut = input.nextLine().split(":");

    int iHourIn = Integer.parseInt(sTimeIn[0]);
    int iMinuteIn = Integer.parseInt(sTimeIn[1]);
    int iHourOut = Integer.parseInt(sTimeOut[0]);
    int iMinuteOut = Integer.parseInt(sTimeOut[1]);

    if(iMinuteIn < iMinuteOut) {
        iMinuteIn = 60 + iMinuteIn;
        iHourIn--;
    }
    int sumHour = iHourIn - iHourOut;
    int sumMinute = iMinuteIn - iMinuteOut;

            //Display Output
            System.out.print(sumHour +"Hour "+ sumMinute + " Minute");


    }
}
Sabesh
  • 310
  • 1
  • 11
  • it would be better to use a split(":") call to seperate hour from minutes, otherwise "5:15" might get you unexpected results – Stultuske Jan 16 '19 at 10:35
  • What result would you get if in is `23:55` and out is `00:05` and what would you expect it to be? – Joakim Danielson Jan 16 '19 at 10:38
  • @Stultuske You're right. I have refractored the code. @ Joakim I assumed out time is always greater than In time. It depends upon Gary's requirement. We can add a extra condition for that – Sabesh Jan 16 '19 at 10:44
  • @SabeshRajendran 00:005 this morning as a time, is greater than 23:55 yesterday. – Stultuske Jan 16 '19 at 10:47