Tim*_*per 119
不需要explode任何东西:
$str_time = "23:12:95";
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = $hours * 3600 + $minutes * 60 + $seconds;
Run Code Online (Sandbox Code Playgroud)
如果您不想使用正则表达式:
$str_time = "2:50";
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = isset($hours) ? $hours * 3600 + $minutes * 60 + $seconds : $minutes * 60 + $seconds;
Run Code Online (Sandbox Code Playgroud)
Gla*_*vić 93
我认为最简单的方法是使用strtotime()函数:
$time = '21:30:10';
$seconds = strtotime("1970-01-01 $time UTC");
echo $seconds;
// same with objects (for php5.3+)
$time = '21:30:10';
$dt = new DateTime("1970-01-01 $time", new DateTimeZone('UTC'));
$seconds = (int)$dt->getTimestamp();
echo $seconds;
Run Code Online (Sandbox Code Playgroud)
函数date_parse()也可用于解析日期和时间:
$time = '21:30:10';
$parsed = date_parse($time);
$seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
Run Code Online (Sandbox Code Playgroud)
如果将解析格式MM:SS与strtotime()或date_parse()将失败(date_parse()在使用strtotime()和DateTime),因为当你这样输入格式xx:yy分析器假设它是HH:MM不MM:SS.我建议检查格式,00:如果只有,则建议MM:SS.
demo strtotime() demo date_parse()
如果你有超过24小时,那么你可以使用下一个功能(它将工作MM:SS和HH:MM:SS格式化):
function TimeToSec($time) {
$sec = 0;
foreach (array_reverse(explode(':', $time)) as $k => $v) $sec += pow(60, $k) * $v;
return $sec;
}
Run Code Online (Sandbox Code Playgroud)
在伪代码中:
split it by colon
seconds = 3600 * HH + 60 * MM + SS
Run Code Online (Sandbox Code Playgroud)
$time = 00:06:00;
$timeInSeconds = strtotime($time) - strtotime('TODAY');
Run Code Online (Sandbox Code Playgroud)
您可以使用该strtotime函数从 返回秒数today 00:00:00。
$seconds= strtotime($time) - strtotime('00:00:00');
Run Code Online (Sandbox Code Playgroud)
试试这个:
$time = "21:30:10";
$timeArr = array_reverse(explode(":", $time));
$seconds = 0;
foreach ($timeArr as $key => $value)
{
if ($key > 2) break;
$seconds += pow(60, $key) * $value;
}
echo $seconds;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
96558 次 |
| 最近记录: |