php 将时间戳转换为秒(2 小时 12 分钟或 2:12:00)

php convert time stamp to seconds (2 hours 12 min or 2:12:00)

您好,我正在尝试将时间戳转换为秒。目前时间戳将以两种形式传输,想为其中一种做准备。但是我认为我用我尝试过的方法让自己变得更难了。

例如输入是

1 小时 1 分 1 秒2 小时 2 分 2 秒 <-- 对于复数

我希望最终输出是下面的示例,这样我就可以将该数字转换为秒数:

01:01:0102:02:02

我不知道情况会怎样,它将是一个通过 url 传递的参数,这是我到目前为止尝试过的方法,但正如我所说,它显示不正确:

$recent_time = htmlspecialchars($_GET["time"]);

$recent_time = preg_replace("/[^0-9,.]/", ":", $recent_time);
    $recent_time = preg_replace("/(.)\1+/", "", $recent_time);

echo $recent_time;

正如您所看到的,我将所有字母替换为冒号,并确保冒号不会重复,因此输出将是 xx:xx:xx,但有时输出不准确,这是我的翻译方式输出到秒:

$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00::", $recent_time);
        sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
        $time_seconds = $hours * 3600 + $minutes * 60 + $seconds;
        $sum_total = $time_seconds + $old_time;

问题是,如果它只是分钟 + 秒,则无法将其正确转换为秒。因此,例如时间是 10 分 13 秒,它将输出 10:13:,但它没有正确地将其转换为秒,因为它不是 00:10:13。我试图截断最后一个冒号,但它仍然无法区分 mintues/sec/hours

$recent_time = substr_replace($recent_time ,"",-1); 

编辑

$converted_time = date('H:i:s',strtotime('$recent_time', strtotime('midnight')));

改为使用 php strtotime 函数

date('H:i:s',strtotime('1 hour 1 minute 1 second', strtotime('midnight'))); // 01:01:01
date('H:i:s',strtotime('2 hours 2 minutes 2 seconds', strtotime('midnight'))); // 02:02:02
date('H:i:s',strtotime('10 minutes 13 seconds', strtotime('midnight'))); // 00:10:13