Difference between revisions of "Find the number of minutes in a HH:MM:SS time string"

From CodeCodex

(Add Seed7 example)
Line 1: Line 1:
 
==Implementations==
 
==Implementations==
 +
 +
 +
===PHP===
 +
<highlightsyntax>
 +
  $array = explode($input);
 +
  $minutes = $array[1];
 +
</highlightsyntax>
 +
 
===Haskell===
 
===Haskell===
 
<highlightsyntax language="haskell">
 
<highlightsyntax language="haskell">

Revision as of 22:43, 20 June 2008

Implementations

PHP

<highlightsyntax>

 $array = explode($input);
 $minutes = $array[1];

</highlightsyntax>

Haskell

<highlightsyntax language="haskell"> import Text.Regex

timeToMinutes :: String -> Double timeToMinutes time_str

 = hours * 60 + minutes + seconds /60
   where [hours, minutes, seconds] = map read $ splitRegex (mkRegex ":") time_str

</highlightsyntax>


Below is the same solution in pointfree style while also reusing some more standard functions. <highlightsyntax language="haskell"> import Text.Regex ttm :: String -> Double ttm = sum . zipWith ($) [(*60), id, (/60)] . map read . (splitRegex . mkRegex) ":" </highlightsyntax>

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;
		}
		
	}

Python

<HIGHLIGHTSYNTAX language="python"> def time_to_minutes(time_str):

   try:
       hours, minutes, seconds = time_str.split(':')
   except ValueError:
       return -1
   return int(hours)*60 + int(minutes) + int(seconds)/60.0

</HIGHLIGHTSYNTAX>

Ruby

def time_to_minutes(time_str)
    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

Seed7

$ include "seed7_05.s7i";
  include "float.s7i";

const func float: time_to_minutes (in string: time_str) is func
  result
    var float: result is 0.0;
  local
    var array string: split_str is 0 times "";
  begin
    split_str := split(time_str, ':');
    result := float parse (split_str[1]) * 60.0 +
              float parse (split_str[2]) +
              float parse (split_str[3]) / 60.0;
  end func;

const proc: main is func
  begin
    writeln(time_to_minutes("09:15:30"));
  end func;