Regular Expressions to Convert Time

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I am trying to write code that will use regular expressions to convert
time entered into minutes. So, lets say someone enters 20m into a
field, then I would have 20 minutes. If someone enters 2h, I would
have 120 minutes. I have that. I want to make sure that they enter in
the correct format also, so if they enter 2h20m, I would have 140
minutes. I am having trouble with making sure that if they enter in
20m2h that it displays an error.

Currently the code I have will give an error anytime I have an h at
the end.

$time_entered = "20m2h";

if (preg_match("/m$/", $time_entered))
    $time = preg_split("/[hm]/", $time_entered);
    if (isset ($time['1']))
        $total_time = (($time['0']*60) + $time['1']);
        $total_time = $time['0'];

elseif (preg_match("/h$/", $time_entered))
    $time = preg_split("/[h]/", $time_entered);
    print_r ($time);
    if (isset ($time['1'])
        <script type="text/javascript">
            alert('The time entered needs to be in a formats like 10h, 30m, or
    $total_time = ($time['0']*60);
    echo "You need to format the time in either minutes (m) or hours

echo $total_time;

Re: Regular Expressions to Convert Time

I'm no RexEx expert but maybe something like this:

preg_match('/^([0-9]*)(h?)([0-9]+)m$/', $time_entered)

personally, I'd just use two form input elements, one for mins and one
for hours...much easier.

Re: Regular Expressions to Convert Time

Oh, and check out this link, it may help:

Re: Regular Expressions to Convert Time

I recommend you modify this script slightly to use your h/m values as
opposed to a standard 00:00 format.


Quoted text here. Click to load it

Site Timeline