有人可以帮我解决这个 PHP 时间戳之谜
我正在尝试根据两个给定日期查找工作日数。
我得到一个字符串日期,例如开始日期:01/10/2019(2019 年 10 月 1 日)并将其分解为数组 => $s
数组 $s 设置如下:
Array ( [0] => 01 [1] => 10 [2] => 2019 )
然后我用它制作了一个 Unix 时间戳:
date('U', mktime(0, 0, 0, $s[1], $s[0], $s[2]));
上述日期转换的结果是 1569884400。
然后我使用循环来运行它,这样我就可以根据给定的 2 个日期找到工作日数..
这是该循环的结果,正如您所看到的,出于某种原因,10 月 27 日会重复。
只是为了澄清这个 PHP 页面的顶部,我设置了时区
date_default_timezone_set('Europe/London');
这是下面结果背后的代码
基于最后日期的总计 $total_days(在本例中为 2019 年 10 月 31 日,即:31 天)
2019 年 10 月应该有 23 个工作日,因为我有 2 个 10 月 27 日,所以我只会得到 22 个工作日。
我在这里做错了什么?
$wk_days = array(1, 2, 3, 4, 5);
$days = 0;
for ($i = 0; $i < $total_days; $i++) {
$tmp = $first + ($i * 86400);
echo $i." x86400 add to ". $first . " ==> " . $tmp. " and the new date is " .date('Y-m-d',$tmp) ."<br/>";
$chk = date('w', $tmp);
if (in_array($chk, $wk_days)) {
$days++;
}
}
0 x86400 add to 1569884400 ==> 1569884400 and the new date is 2019-10-01
1 x86400 add to 1569884400 ==> 1569970800 and the new date is 2019-10-02
2 x86400 add to 1569884400 ==> 1570057200 and the new date is 2019-10-03
3 x86400 add to 1569884400 ==> 1570143600 and the new date is 2019-10-04
4 x86400 add to 1569884400 ==> 1570230000 and the new date is 2019-10-05
...
23 x86400 add to 1569884400 ==> 1571871600 and the new date is 2019-10-24
24 x86400 add to 1569884400 ==> 1571958000 and the new date is 2019-10-25
25 x86400 add to 1569884400 ==> 1572044400 and the new date is 2019-10-26
26 x86400 add to 1569884400 ==> 1572130800 and the new date is 2019-10-27 //***
27 x86400 add to 1569884400 ==> 1572217200 and the new date is 2019-10-27 //***
28 x86400 add to 1569884400 ==> 1572303600 and the new date is 2019-10-28
29 x86400 add to 1569884400 ==> 1572390000 and the new date is 2019-10-29
30 x86400 add to 1569884400 ==> 1572476400 and the new date is 2019-10-30
最佳答案
你不需要那么复杂的东西。您可以有一个简单的 while 循环并计算工作日。这可能不是最有效的方法,但它应该有效。
function getNoOfWeekdays(string $startdate, string $enddate, string $format = 'd/m/Y'): int
{
$start = date_create_from_format($format, $startdate);
$end = date_create_from_format($format, $enddate);
$count = 0;
while ($start <= $end) {
if ($start->format('N') < 6) $count++;
$start->modify('+1 days');
}
return $count;
}
关于PHP 日期 - Unix 时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59752793/