【发布时间】:2017-07-18 19:44:41
【问题描述】:
我有以下格式的日期时间:
开始时间:2017-07-16 20:00
结束:2017-07-16 23:30
开始:2017-07-18 21:30
结束:2017-07-19 00:30
我需要从这些间隔中得知一个月内在 18:00-22:00 和 22:00-06:00 之间总共花费了多少小时(以 0.5 为增量)。
提前感谢您的任何提示。
我目前的代码是这样的,但我不确定它是否涵盖了所有时间范围的可能性:
<?php
date_default_timezone_set("UTC");
$start = array(
"2017-07-16 21:30:00",
"2017-07-16 18:00:00"
);
$end = array(
"2017-07-17 00:30:00",
"2017-07-16 18:30:00"
);
$amount_low = 0;
$amount_high = 0;
for($i = 0; $i < sizeof($start); $i++) {
$start_time = date("H:i:s", strtotime($start[$i]));
$end_time = date("H:i:s", strtotime($end[$i]));
$start_date = date("Ymd", strtotime($start[$i]));
$end_date = date("Ymd", strtotime($end[$i]));
// getting chunk before 22:00 if
if(
(strtotime($start[$i]) >= strtotime($start_date . " 18:00") && strtotime($start[$i]) < strtotime($start_date . " 22:00"))
&&
$start_date < $end_date
) {
$interval_low = strtotime($start_date . " 22:00") - strtotime($start[$i]);
$amount_low += ceil($interval_low / 1800) / 2;
}
//amount_high
if(strtotime($start[$i]) > strtotime($start_date . " 22:00") && strtotime($start[$i]) < strtotime($start_date . " 06:00")) {
$interval_high = strtotime($end[$i]) - strtotime($start[$i]); //needs further things
$amount_high += ceil($interval_high / 1800) / 2;
} elseif (strtotime($start[$i]) < strtotime($start_date . " 22:00") && strtotime($end[$i]) > strtotime($start_date . " 22:00")) {
$interval_high = strtotime($end[$i]) - strtotime($start_date . " 22:00");
$amount_high += ceil($interval_high / 1800) / 2;
} else {
$interval_low = strtotime($end[$i]) - strtotime($start[$i]);
$amount_low += ceil($interval_low / 1800) / 2;
}
}
echo $amount_low;
echo "\n$amount_high";
?>
【问题讨论】:
-
你能提供一些代码和预期的输出吗?第一个例子的答案是 2 小时和 1.5 小时吗?
-
@Andreas 是的,对于第一个示例,它确实应该给出上述金额。我尝试实现的代码与下面提到的两个日期之间的时间差相同。
-
我们要求提供代码的原因是因为我们想知道您尝试过什么/尝试过什么。并且不必从头开始。并使用与您相同的变量,这样您就不必将它们更改为您的变量。
-
代码被添加到问题中,我相信这不是重复的。
-
太晚了。以此为你的教训。写下你的问题,这样就不会有任何后续问题或任何不清楚的地方。我的建议。删除这个问题并写一个新问题。记住这一课。
标签: php datetime dateinterval