【发布时间】:2012-05-21 04:04:40
【问题描述】:
我有一个开始时间和结束时间,它们总是在准确的一个小时 :00 或 :15、:30、:45 开始或结束。
例如:
00:30 21-05-2012 // startdate and time
18:15 22-05-2012 // enddate and time (+1 day)
如果时间进入傍晚或夜间,我必须额外收取 % 的费用。
所以我有 2 个数组,一个用于晚上时间,一个用于晚上时间,看起来像这样。
$eveningHours = array(
'18:00',
'18:15',
'18:30',
// etcetera
'00:00'
);
上面的数组基本上涵盖了从 18:00 到 00:00 的时间,因为这些时间正落入晚上。
夜间时间也是如此,它们涵盖从 00:00 到 07:00 的时间。
由于开始时间和结束时间总是准确地落在 :00 或 :15、:30、:45.. 我在开始日期时间和结束日期时间之间运行一个循环,间隔为 15 分钟,然后在每个间隔上运行我检查当前的间隔时间是否是夜间/晚上时间,然后将 +15 添加到晚上/夜间时间计数器,最后我将其除以 60 以获得总小时数。
但不知何故,它总是有 15 分钟到多或 15 分钟到少......我已经尝试了几乎所有的东西,但无法让它正常工作..
例如,开始时间是 00:30,它已经在第一个时间间隔上增加了 15 分钟:
00:30(计数器:+15) 00:45(计数器:+15)
总共需要 30 分钟,但如果您从 00:30 到 00:45 工作,则应该只有 15 分钟。所以我认为这就是出错的地方。我只需要一种方法来修复它。我已经尝试了很多方法,方法是用 -15 分钟启动计数器,或者检查开始时间或结束时间是否在一个小时范围内,然后将计数器设置为 -15 或 + 15分钟..但这也出错了。
编辑这是循环的基础:
$start_time = mktime($_POST['worked_start_hour'], $_POST['worked_start_min'], 0, date("m"), date("d", strtotime("+1 days")), date("Y")); // +1 day for testing purpose
$end_time = mktime($_POST['worked_end_hour'], $_POST['worked_end_min'], 0, date("m"), date("d", strtotime("+2 days")), date("Y")); // +2 days for testing purpose
$date['start_h_i'] = date("Y-m-d H:i", $start_time); # Start date: yyyy-mm-dd hours:minutes
$date['end_h_i'] = date("Y-m-d H:i", $end_time); # End date: yyyy-mm-dd hours:minutes
$counter['eveningMinutes'] = 0;
$counter['nightMinutes'] = 0;
$eveningHours = array(
'18:00',
'18:15',
'18:30',
'18:45',
'19:00',
'19:15',
'19:30',
'19:45',
'20:00',
'20:15',
'20:30',
'20:45',
'21:00',
'21:15',
'21:30',
'21:45',
'22:00',
'22:15',
'22:30',
'22:45',
'23:00',
'23:15',
'23:30',
'23:45',
'00:00'
);
$nightHours = array(
'00:00',
'00:15',
'00:30',
'00:45',
'01:00',
'01:15',
'01:30',
'01:45',
'02:00',
'02:15',
'02:30',
'02:45',
'03:00',
'03:15',
'03:30',
'03:45',
'04:00',
'04:15',
'04:30',
'04:45',
'05:00',
'05:15',
'05:30',
'05:45',
'06:00',
'06:15',
'06:30',
'06:45',
'07:00'
);
while (strtotime($date['start_h_i']) <= strtotime($date['end_h_i'])) {
if (in_array(date("H:i", strtotime($date['start_h_i'])), $eveningHours)) {
$counter['eveningMinutes'] = $counter['eveningMinutes'] + 15;
}
if (in_array(date("H:i", strtotime($date['start_h_i'])), $nightHours)) {
$counter['nightMinutes'] = $counter['nightMinutes'] + 15;
}
$date['start_h_i'] = date ("Y-m-d H:i", strtotime("+15 minutes", strtotime($date['start_h_i']))); // 15 minutes interval
} // end while
希望有人能在这里发光,谢谢!
有人吗?
【问题讨论】:
-
请分享那个循环,因为那确实是有问题的代码。
-
为什么不直接计算
endTime - startTime? -
据我了解,您在晚上和夜间都列出
'00:00'?还是打错字了? -
@Fabricio,是的,没错。但我也已经尝试从 00:15 开始 nightHours 数组。但这没有帮助。 @animuson如果您正确阅读了我的问题..我不想获得整个开始和结束时间的总小时数,我只需要夜间和晚上的小时数..我需要这些时间来计算额外的百分比费用标准小时费率。
-
@Wiseguy 我已将代码添加到帖子中。