I'm trying to figure out the best way to convert a string containing a time to an integer number of milliseconds. I'm using a suboptimal way using a bunch of preg_match()'s and some array handling, but I was wondering if there was an elegant way.
Here are some example stopwatch times (some wouldn't actually be seen on a stopwatch but need to be converted anyway):
3:34:05.81
34:05
5 (just 5 second开发者_StackOverflow社区s)
89 (89 seconds)
76:05 (76 minutes, 5 seconds)
Millseconds will not extend past 2 decimal places. You can give me an example using either PHP or Javascript regex functions.
Thanks!
I know it is solved.. but this is just an idea for javascript..
String.prototype.sw2ms = function() {
var a = [86400000, 3600000, 60000, 1000];
var s = this.split(/\:/g);
var z = 0;
while (s.length && a.length)
z += a.pop() * Number(s.pop());
return z;
};
alert("3:45:03.51".sw2ms());
alert("10:37".sw2ms());
alert("05.81".sw2ms());
alert("5".sw2ms());
I wouldn't bother using a regexp in this case.
Simply explode
(split) the strings with ':', and perform a backward analysis - you always have seconds (and maybe milliseconds). Starting with array[lastelement] (seconds) then the previous...
For instance
In PHP
function getMilliseconds($input)
{
$a = explode(':', $input);
$n = count($a); // number of array items
$ms = 0; // milliseconds result
if ($n > 0)
{
$b = explode('.', $a[$n-1]);
if (count ($b) > 1)
{
$m = $b[1];
while (strlen($m) < 3) $m .= '0'; // ensure we deal with thousands
$ms += $m;
}
$ms += $b[0] * 1000;
if ($n > 1) // minutes
{
$ms += $a[$n-2] * 60 * 1000;
if ($n > 2) // hours
{
$ms += $a[$n-3] * 60 * 60 * 1000;
}
}
}
return $ms;
}
In JavaScript
(just a PHP to Javascript conversion)
function getMilliseconds(input)
{
var a = input.split(':');
var n = a.length; // number of array items
var ms = 0; // milliseconds result
if (n > 0)
{
var b = a[n-1].split('.');
if (b.length > 1)
{
var m = b[1];
while (m.length < 3) m += '0'; // ensure we deal with thousands
ms += m - 0; // ensure we deal with numbers
}
ms += b[0] * 1000;
if (n > 1) // minutes
{
ms += a[n-2] * 60 * 1000;
if (n > 2) // hours
{
ms += a[n-3] * 60 * 60 * 1000;
}
}
}
return ms;
}
Using regex gives no clear advantage:
function parseStopwatchTime(time) {
var splitTime = time.split(':'), // explode function in PHP
secs = 0;
if(time.length < 1 || time.length > 3) {
return NaN;
}
for(var i = 0; i < time.length; i++) {
secs *= 60;
secs += +splitTime[i]; // JavaScript's unary plus operator
// casts from a string to a number
// so that it can safely be added.
}
return secs * 1000; // convert from seconds to milliseconds
}
More code would be needed if your stopwatch counts in days (still no regex needed), but just this is sufficient for hours, minutes, and (fractions of) a second.
精彩评论