我想用php或cakephp函数减去日期,示例:
$date1 = '2016-05-19';
$date2 = '2016-05-23';
我想减去没有星期日的日期,从例子中我想要的结果是3,而不是4,因为4-1(星期日),
我已经尝试使用新的Datetime php,如以下代码,
$receipt_date = new DateTime($air_way_bill['AirWayBill']['receive_date']);
$date = new DateTime($air_way_bill['AirWayBill']['date']);
$difference = $receipt_date->diff($date);
但是结果是4,我怎么能用星期天减去这个范围?有什么步骤或方法可以做到我的意思吗?
提前感谢。。。
【结案】:
正确答案:
// ============================= 1 ==================== //
$receipt_date = new DateTime('2016-05-19');
$date = new DateTime('2016-05-23');
$difference = $receipt_date->diff($date);
$daterange = new DatePeriod($receipt_date, new DateInterval('P1D'), $date);
$count = 0;
foreach($daterange as $date){
if(!($date->format("w"))) {
$count++;
}
}
echo ($difference->days)-$count;
//========================================//
// ============================= 2 ==================== //
function getSubtrackedDayCountWithoutSundaysButWithAllOtherDaysUsingDateTimeFunctions($startDate, $endDate)
{
$days = $startDate->diff($endDate, true)->days;
$sundays = intval($days / 7) + ($startDate->format('N') + $days % 7 >= 7);
return intval($days)-Sundays;
}
//=================================================//
//==========================这是我的实验================//
$date = date('Y-m-d', strtotime($air_way_bill['AirWayBill']['date']));
$receive_date = date('Y-m-d', strtotime($air_way_bill['AirWayBill']['receive_date']));
$date_diff = round(abs(strtotime($receive_date) - strtotime($date)) / 86400);
$weeks = round(abs(strtotime($receive_date) - strtotime($date)) / (86400 * 7));
echo $date_diff - $weeks;
//=================================================//
非常感谢。。。
您可以找到总天数,然后找到该范围内的星期日数。最后从总天数中减少这些天数:
<?php
$receipt_date = new DateTime('2016-05-19');
$date = new DateTime('2016-05-23');
$difference = $receipt_date->diff($date);
$daterange = new DatePeriod($receipt_date, new DateInterval('P1D'), $date);
$count = 0;
foreach($daterange as $date){
if(!($date->format("w"))) {
$count++;
}
}
echo ($difference->days)-$count;
演示
我编写了一个函数来满足您的要求。
function getSubtrackedDayCountWithoutSundaysButWithAllOtherDaysUsingDateTimeFunctions($startDate, $endDate)
{
$days = $startDate->diff($endDate, true)->days;
$sundays = intval($days / 7) + ($startDate->format('N') + $days % 7 >= 7);
return intval($days)-$sundays;
}