gpt4 book ai didi

php - 用数字字符串计算时间(HH :MM:SS)

转载 作者:可可西里 更新时间:2023-11-01 00:25:54 25 4
gpt4 key购买 nike

我想知道在 PHP/Codeigniter 中是否可以减去时间格式为

的值

HH:MM:SS

例如:

$time1 = "12:45:03";
$time2 = "14:03:48";

$timelength = $time2- $time1;

有任何建议或指向代码示例的链接吗?

最佳答案

这就像

//function to convert seconds into hour:minute:second
function sec2hms ($sec, $padHours = false)
{

// start with a blank string
$hms = "";

// do the hours first: there are 3600 seconds in an hour, so if we divide
// the total number of seconds by 3600 and throw away the remainder, we're
// left with the number of hours in those seconds
$hours = intval(intval($sec) / 3600);

// add hours to $hms (with a leading 0 if asked for)
$hms .= ($padHours)
? str_pad($hours, 2, "0", STR_PAD_LEFT). ":"
: $hours. ":";

// dividing the total seconds by 60 will give us the number of minutes
// in total, but we're interested in *minutes past the hour* and to get
// this, we have to divide by 60 again and then use the remainder
$minutes = intval(($sec / 60) % 60);

// add minutes to $hms (with a leading 0 if needed)
$hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT). ":";

// seconds past the minute are found by dividing the total number of seconds
// by 60 and using the remainder
$seconds = intval($sec % 60);

// add seconds to $hms (with a leading 0 if needed)
$hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);

// done!
return $hms;

}

$subtracted_time = strtotime($time2) - strtotime($time1); //gives difference in seconds
echo(sec2hms($subtracted_time));

函数 sec2hms 来源 http://www.laughing-buddha.net/php/lib/sec2hms/

关于php - 用数字字符串计算时间(HH :MM:SS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6859552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com