我要做的是以DD-MM-YYYY格式获取$ distinct_expiries(2017年10月26日)前$ time_to_expiry($ 6)天的日期($ date_before_that_expiry)
但是,如果返回的日期是数组($ trading_holiday_array),那么它应该在前一天移动返回的日期($ date_before_that_expiry)。这是递归完成的。
例如:如果我在2017年10月20日获得日期,那么它应该在2017年10月18日返回,而不是19日,因为2017年10月19日也是($ trading_holiday_array)的一部分。
这是我放下的代码,但它进入了无限循环:
<?php
$distinct_expiries='26-Oct-2017';
$time_to_expiry=6;
$trading_holiday_array = array('19-Oct-2017', '20-Oct-2017');
$date_before_that_expiry = date('d-M-Y', strtotime("-$time_to_expiry days", strtotime($distinct_expiries)));
while(in_array($date_before_that_expiry, $trading_holiday_array)) {
$new_lookback= -(1+$time_to_expiry)." days";
$date_before_that_expiry = date('d-M-Y', strtotime("$new_lookback", strtotime($distinct_expiries)));
}
echo $date_before_that_expiry;
?>
请协助。
答案 0 :(得分:1)
这是一个简单整理逻辑的实现,您只需要转移到DateTime。
<?php
$blocked = [
new DateTime("2017-10-19"),
new DateTime("2017-10-20")
];
$timeToExpiry = new DateInterval("P6D"); // read as 'Period: 6 Days'. "P1Y3M" would be one year, 3 months
function getFirstAllowed(DateTime $startdate, Array $blocked, DateInterval $timeToExpiry) {
$target = $startdate->sub($timeToExpiry);
$oneDayInterval = new DateInterval("P1D");
while(in_array($target, $blocked)) {
$target->sub($oneDayInterval);
}
return $target;
}
// testing
echo getFirstAllowed(new DateTime("2017-10-25"), $blocked, $timeToExpiry)->format("Y-m-d")."<br>"; // 2017-10-18
echo getFirstAllowed(new DateTime("2017-10-26"), $blocked, $timeToExpiry)->format("Y-m-d")."<br>"; // 2017-10-18
echo getFirstAllowed(new DateTime("2017-10-31"), $blocked, $timeToExpiry)->format("Y-m-d")."<br>"; // 2017-10-25
同样转移到DateTime:
create-react-app
答案 1 :(得分:0)
我想我在修补了一下后得到了答案:
<?php
$distinct_expiries='26-Oct-2017';
$time_to_expiry=6;
$trading_holiday_array = array('19-Oct-2017', '20-Oct-2017');
$date_before_that_expiry = date('d-M-Y', strtotime("-$time_to_expiry days", strtotime($distinct_expiries)));
while(in_array($date_before_that_expiry, $trading_holiday_array)) {
$time_to_expiry+=1;
$date_before_that_expiry = date('d-M-Y', strtotime("-$time_to_expiry days", strtotime($distinct_expiries)));
}
echo $date_before_that_expiry;
?>
我使用相同的$ time_to_expiry,这导致循环变为无限。 :-P
感谢任何进一步的改进。