Find the number of minutes in a HH:MM:SS time string

From CodeCodex

Revision as of 05:16, 9 May 2007 by 71.231.110.73 (Talk)

Implementations

Java

	/**
	 * Turns a period of time into the number of minutes represented
         * (eg. 06:30:15 returns 360.25)
	 * @param hourFormat The string containing the hour format "HH:MM:SS"
	 * @return The number of minutes represented, or -1 if the date could not be processed.
	 */
	public static double parseTimeToMinutes(String hourFormat) {
		
		double minutes = 0;
		String[] split = hourFormat.split(":");
		
		try {
			
			minutes += Double.valueOf(split[0])*60;
			minutes += Double.valueOf(split[1]);
			minutes += Double.valueOf(split[2])/60;
			return minutes;
		
		} catch (Exception e) {
			return -1;
		}
		
	}

Ruby

def time_to_minutes(time_str)
  begin
    split_str = time_str.split(":")
    return (split_str[0].to_f * 60) + (split_str[1].to_f) + (split_str[2].to_f / 60)
  rescue Exception => e
    # do any additional error handling here
    return -1
  end
end