Grow your CSS skills. Land your dream job.

Last updated on:

English Time to Seconds

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']);
}

Reference URL

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".