PHP和两个不同的分
我有两个不同的休息时间PHP和两个不同的分
- 默认休息时间
- 额外的休息时间
在这里,我要总结的两次,显示12小时格式
EX:
$default_time = "00:30";
$extra_time = "00:25";
我的预期输出:00:55
但现在显示01:00
这是我的代码
$default_time = $work_data->break_time;
$break_time = $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));
这里是你可以通过计算总时间的函数将参数传递给函数。
$小时,$分钟应该变量,它是零
$default_time = "00:30";
$break_time = "00:25";
function calculate_total_time() {
$i = 0;
foreach(func_get_args() as $time) {
sscanf($time, '%d:%d', $hour, $min);
$i += $hour * 60 + $min;
}
if($h = floor($i/60)) {
$i %= 60;
}
return sprintf('%02d:%02d', $h, $i);
}
// use example
echo calculate_total_time($default_time, $break_time); # 00:55
<?php
$time = "00:30";
$time2 = "00:25";
$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
print_r($result);
?>
我想知道什么是背后的strtotime逻辑倍($时间2) - strtotime(“00:00:00”) –
有一个函数调用strtotime
功能太多。
你应该排除在最后一行strtotime()
调用,如$total_break
已经是UNIX时间戳:
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",$total_break);
如果我删除strtotime()在回声输出是** 03:26 ** –
的问题是,你想添加过多的具体时间戳,但是你在做什么试图实现增加两个持续时间。所以你需要将这些时间戳转换为持续时间。为此,你需要一个基地,在你的情况下是00:00。
$base = strtotime("00:00");
$default_time = $work_data->break_time;
$default_timestamp = strtotime($default_time);
$default_duration = $default_timestamp - $base; // Duration in seconds
$break_time = $work_data->extra_time;
$break_timestamp = strtotime($break_time);
$break_duration = $break_timestamp - $base; // Duration in seconds
$total_break = $default_duration + $break_duration; // 55 min in seconds
// If you want to calculate the timestamp 00:55, just add the base back to it
echo date("H:i", $base + $total_break);
考虑使用标准DateTime
和DateInterval
类。所有你需要的是你的第二个变量的值转换为interval_spec
格式(见http://php.net/manual/en/dateinterval.construct.php了解详细信息):
$defaultTime = "00:30";
$breakTime = "PT00H25M"; // Or just 'PT25M'
$totalBreak = (new DateTime($defaultTime))->add($breakTime);
echo $totalBreak->format('H:i');
你可以尝试下面的代码片段:
$time1 = explode(":", $default_time);
$time2 = explode(":", $break_time);
$fulltime = ($time1[0] + $time2[0]) * 60 + $time1[1] + $time2[1];
echo (int)($fulltime/60) . ":" . ($fulltime % 60);
下面的代码使用,你一定会得到你的答案。
$default_time = "00:30:00";
$extra_time = "00:25:00";
$secs = strtotime($extra_time)-strtotime("00:00:00");
$result = date("H:i:s A",strtotime($default_time)+$secs);
echo $result;die;
您可以根据需要修改上述代码。
你可以尝试以下方法:
$default_time = $work_data->break_time;
$date_start = new DateTime($default_time);
$break_time = $work_data->extra_time;
$interval = new DateInterval("PT" . str_replace(":", "H", $break_time) . "M");
$date_end = $date_start->add($interval);
echo $date_end->format("H:i");
注意,这不能解释其跨越24小时内
谢谢工作好.. –