Wednesday, September 21, 2016

How to compute the number of hours between two given times in Java

/**
 * @(#)testcase1.java
 *
 *
 * @author : A. Dichosa
 * @version 1.00 2016/9/21
 */


public class testcase1 {
    public static void main(String [] args) {
    String timein,timeout;
    double time_interval=0; 
        
    timein="8:00";
    timeout="12:00";
    time_interval=GetHourInterval(timein,timeout);
       

    System.out.println(String.format("%.2f",time_interval));    
    }   
    
    /*
     *Description: This method computes the hour interval between two times. It takes two parametes in and out.
     */
    private static double GetHourInterval(String in, String out){
    String timein_arr[];
    String timeout_arr[];
   
    double in_hours=0;
    double out_hours=0;
    double total_hours=0;
   
    timein_arr=in.split(":");
    timeout_arr=out.split(":");
   
    in_hours=Double.parseDouble( timein_arr[0])+ (Double.parseDouble(timein_arr[1])/60);
    out_hours=Double.parseDouble( timeout_arr[0])+ (Double.parseDouble(timeout_arr[1])/60);
    total_hours=out_hours-in_hours;
   
    return total_hours;
   
    }
    
}

No comments:

Post a Comment