PHP中的日期对我来说是一场噩梦,所以请帮助我找其他编码员...我想通知客户他们的订单交付日期。它的工作原理如下:
我有2个运输区,A& B. A区的订单每周一,周三和周五交付。星期五,而B区是星期二,星期四,星期六。对于每个订单,交货日计划在下一个可用日期,具体取决于区域。请注意,如果有人在星期一下订单,货物将在下一个可用日期交付,即B区周二和A区周三。
如何计算下一个可用的交货日期并通知客户?
感谢。
答案 0 :(得分:3)
这肯定不是最快或最聪明的答案,但阅读代码会很愉快。
假设我们在A区发货:
$dates = array(
new DateTime('next monday'), // magic!
new DateTime('next wednesday'),
new DateTime('next friday'),
);
// Seems to work because since PHP 5.2.2 DateTime objects
// can be compared with the < and > operators
$shippingDate = min($dates);
echo $shippingDate->format('Y-m-d');
你可能想看看PHP中可用的relative date formats,这是“下一个星期一”魔术发生的部分。有关使用$shippingDate
可以执行的操作的信息,请参阅有关课程DateTime
的文档。
为了完整性,这里有一个更老的版本,不需要PHP 5.3,也应该更快(尽管速度在这里几乎无关紧要)。我不喜欢它,因为验证它是否正常工作并不容易。与上面的版本相比,这个版本在我第一次编写它时有一个错误。简单就是好。
$today = date('w');
// These values are from http://www.php.net/manual/en/function.date.php
$shippingDays = array(
1, // mon
3, // wed
5, // fri
);
// Each of these weekdays is how many days into the future?
foreach($shippingDays as &$day) {
$day = (7 + $day - $today) % 7;
}
// Get the earliest one, but not if it's today
// array_filter is used to remove a possible 0
$daysInFuture = min(array_filter($shippingDays));
$shippingDate = new DateTime('+'.$daysInFuture.' days');
echo $shippingDate->format('Y-m-d');
<强> See it in action 强>
答案 1 :(得分:1)
试试这个:
// Info
$date = array(date("d"), date("m"), date("Y"));
$zone = "A";
// ------
$zones = array("A" => array(1 => "Monday",
3 => "Wednesday",
5 => "Friday")
,"B" => array(2 => "Tuesday",
4 => "Thursday",
6 => "Saturday"));
$found = false;
$days_plus = 1; // always next day
// Retrieve last day from the zone
end($zones[$zone]);
$last_day = key($zones[$zone]);
do {
$mk = mktime(0, 0, 0, $date[1], ($date[0] + $days_plus), $date[2]);
$week = date("w", $mk);
// if week not passed last day of zone
if ($week <= $last_day)
{
if (!isset($zones[$zone][$week]))
{
$days_plus++;
}
else
{
$found = true;
}
}
else
{
$days_plus++;
}
} while (!$found);
echo "Next date: " . date("d/m/Y - l", $mk);
答案 2 :(得分:0)
$timestamp = strtotime('next Monday');
$date = date('Y-m-d', $timestamp);