English Time to Seconds

Avatar of Chris Coyier
Chris Coyier on

Just type in the time you want converted to seconds in english (e.g. “1 hour and 30 minutes”) and it will be converted to an integer of seconds (e.g. 5400). Thanks to Baylor Rae.

function time2seconds($time) {

 preg_match_all('/(\d+ [a-z]+)/', $time, $matches);
 
 $matches = $matches[0];

 $formats = array();

 foreach ($matches as $format) {
   preg_match('/(\d+)\s?([a-z]+)/', $format, $f);
   $time = $f[1];
   $type = $f[2];
   $formats[$type] = $time;
 }

 $output = array(
     'years' => 0,
     'months' => 0,
     'days' => 0,
     'hours' => 0,
     'minutes' => 0,
     'seconds' => 0
 );

 foreach ($formats as $format => $time) {
   if( $time == 0 )
     continue;

   switch ($format) {
     case 'year' :
     case 'years' :
       $output['years'] = $time * 12 * 30 * 24 * 60 * 60;
     break;

     case 'month' :
     case 'months' :
       $output['months'] = $time * 30 * 24 * 60 * 60;
     break;

     case 'day' :
     case 'days' :
       $output['days'] = $time * 24 * 60 * 60;
     break;

     case 'hour' :
     case 'hours' :
       $output['hours'] = $time * 60 * 60;
     break;

     case 'minute' :
     case 'minutes' :
       $output['minutes'] = $time * 60;
     break;

     case 'second' :
     case 'seconds' :
       $output['seconds'] = $time;
     break;
   }

 }

 return $output['years'] + $output['months'] + $output['days'] + $output['hours'] + $output['minutes'] + $output['seconds'];
}

Simple Usage

Form submits “time”:

<form method="post">
	<label for="time">Time</label><br />
	<input type="text" name="time" id="time" size="50" value="<?php echo (isset($_POST['time'])) ? $_POST['time'] : '1 hour 30 minutes' ?>" />
	<button name="submit">Test!</button>
</form>

If “time” is set, use the function and echo what is returned:

if (isset($_POST)) {
  echo time2seconds($_POST['time']);
}