Popular Posts

Showing posts with label time between two clocks. Show all posts
Showing posts with label time between two clocks. Show all posts

Thursday, February 16, 2017

Calculate Time Difference Between Two Clocks in String Format

The other day I was looking for calculating the time difference between two clocks in String format. I could find a better solution, so I wrote a custom one. Take a look at the Java Code below:

   1:  public static String calTimeDifference(String startHour, 
       String startMin, String endHour, String endMin){
   2:   
   3:  String total = "0";     
   4:   
   5:  if (!StringUtils.isEmpty(startHour) && 
       !StringUtils.isEmpty(startMin) && 
       !StringUtils.isEmpty(endHour) && 
       !StringUtils.isEmpty(endMin){
   6:   
   7:   int stHr = Integer.parseInt(startHour) * 60 ;
   8:   
   9:   int stMn = Integer.parseInt(startMin);
  10:   
  11:   int enHr = Integer.parseInt(endHour) * 60 ;
  12:   
  13:   int enMn = Integer.parseInt(endMin);
  14:   
  15:   int startTime = stHr + stMn;
  16:   
  17:   int endTime = enHr + enMn;
  18:   
  19:    if (endTime > startTime){
  20:   
  21:     int durationHr = (endTime - startTime)/60;
  22:   
  23:     int durationMn = (endTime - startTime)%60;
  24:   
  25:     total = Integer.toString(durationHr) + " Hr and "
         + Integer.toString(durationMn) + " Min" ;
  26:   
  27:      }
  28:   
  29:     else{
  30:   
  31:      total = "Ending Time cannot be before Starting Time";
  32:   
  33:      }
  34:   
  35:    }       
  36:   
  37:   return total;
  38:   
  39:  }


The above code should work as long as you keep in mind the pre and post conditions.

Pre-Condition:
This function assumes that all four parameters are present so if even one of them is missing it will return zero.

Post-Condition:
This function will also make sure that the ending time cannot be before the starting time if it is it will return the error message.