详谈time_to_sec函数

发布时间:2023-05-19

一、timetosec函数

timetosec函数用于将一段时间字符串转换成秒数。

function timetosec($time) {
    $hours = substr($time, 0, -4);
    $minutes = substr($time, -4, 2); 
    $seconds = substr($time, -2); 
    return $hours * 3600 + $minutes * 60 + $seconds;
}

该函数可以处理时间字符串,如"01:12:30",并将其转换为相应的秒数。 例如:

echo timetosec("01:12:30"); // 4350

二、timetoseconds

timetoseconds函数用于将一个时间段转换成秒数,例如"5minutes"或"2hours30minutes"。

function timetoseconds($time) {
    preg_match_all('/(\d+)\s*(minutes|minute|hours|hour)/', $time, $matches);
    $seconds = 0;
    foreach ($matches[1] as $key => $value) {
        if ($matches[2][$key] == 'hour' || $matches[2][$key] == 'hours') {
            $seconds += $value * 3600;
        }
        if ($matches[2][$key] == 'minute' || $matches[2][$key] == 'minutes') {
            $seconds += $value * 60;
        }
    }
    return $seconds;
}

该函数可以将一个时间段字符串,如"5minutes"或"2hours30minutes",转换成相应的秒数。 例如:

echo timetoseconds("5minutes"); // 300
echo timetoseconds("2hours30minutes"); // 9000

三、timetosecond

timetosecond函数是timetoseconds的简短版,只能接受"minutes"或"hours"两种时间单位。

function timetosecond($time) {
    if (strpos($time, "minutes") !== false) {
        return intval($time) * 60;
    }
    else if (strpos($time, "hours") !== false) {
        return intval($time) * 3600;
    }
}

该函数可以将一个时间段字符串,如"5minutes"或"2hours",转换成相应的秒数。 例如:

echo timetosecond("5minutes"); // 300
echo timetosecond("2hours"); // 7200

四、timetosec(133000)

timetosec函数可以将一个整数时间转换成相应的时间字符串。

function timetosec($time) {
    $hours = floor($time / 3600);
    $time %= 3600;
    $minutes = floor($time / 60);
    $seconds = $time % 60; 
    return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}

该函数可以将一个整数时间,如"133000",转换成相应的时间字符串,例如"01:13:20"。 例如:

echo timetosec(133000); // 01:13:20

五、timetosec(103000)

timetosec函数可以将一个整数时间转换成相应的时间字符串。

function timetosec($time) {
    $hours = floor($time / 3600);
    $time %= 3600;
    $minutes = floor($time / 60);
    $seconds = $time % 60; 
    return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}

该函数可以将一个整数时间,如"103000",转换成相应的时间字符串,例如"00:57:10"。 例如:

echo timetosec(103000); // 00:57:10

六、time to sec

time to sec函数可以将一个时间字符串,如"6 minutes 30 seconds",转换成相应的秒数。

function time_to_sec($time) {
    $parts = array_reverse(explode(' ', $time));
    $seconds = 0;
    $multipliers = array(
        'hour' => 3600,
        'hours' => 3600,
        'minute' => 60,
        'minutes' => 60,
        'second' => 1,
        'seconds' => 1
    );
    foreach ($parts as $part) {
        if (isset($multipliers[$part])) {
            $seconds += $multipliers[$part] * array_pop($parts);
        }
    }
    return $seconds;
}

该函数可以将一个时间字符串,如"6 minutes 30 seconds",转换成相应的秒数。 例如:

echo time_to_sec("6 minutes 30 seconds"); // 390
echo time_to_sec("2 hours 30 minutes 45 seconds"); // 9045