我需要为我的用户提供一种方法来选择未来几天(包括今天)上午11点和下午4点的时间段,总共有8个选项。当然,如果今天已经过了上午11点或下午4点,那么我就不应该给他们看过期的选项。
因此,例如,如果当前是2月28日中午,那么我需要向用户显示以下8个选项:
28-Feb-13 at 4pm
01-Mar-13 at 11am
01-Mar-13 at 4pm
02-Mar-13 at 11am
02-Mar-13 at 4pm
03-Mar-13 at 11am
03-Mar-13 at 4pm
04-Mar-13 at 11am
另外,我需要一种方法来存储MySQL中的这些选项,以便我现在他们选择的日期/时间,并将其与他们的注册信息一起保存到DB。
这听起来很容易用语言解释,但是我有一个难以置信的困难的时间弄清楚如何在PHP中编程。
我如何使用DateTime()
类做到这一点?
<?php
$hours = array(11,16);
$outputCount = 8;
$now = new DateTime();
$t = clone $now;
$dates = array();
$i=0;
while (count($dates)<$outputCount) {
$t->setTime($hours[++$i % count($hours)],0,0);
if ($t>$now) {
$dates[] = clone $t;
}
if ($t->format('G') == max($hours)) {
$t->modify('+1 day');
}
}
print_r($dates);
你只需要创建一个dateTime为"now",然后检查你是否在上午11点之前,然后决定将你的时间移到上午11点或下午4点,然后增加到检索你的8个值。
下面是一段可以处理这些东西的代码:// create a "now" date time
$now = new DateTime();
// create a "now at 11am" date time
$nowAt11am = new DateTime();
$nowAt11am->setTime(11, 0, 0);
// Compare the interval between now and now at 11am
$interval = $now->diff($nowAt11am);
// Initialize the increment even/odd
$incementEvenOdd = 0;
// Check interval
if ($interval->invert == 1)
{
// $interval < 0 => we are before $nowAt11am, set to 11 am
$now = $nowAt11am;
$incementEvenOdd = 0;
}
else
{
// $interval > 0 => we are after $nowAt11am, set to 4 pm
$now->setTime(16, 0, 0);
$incementEvenOdd = 1;
}
$dayAndHours = array();
$dayAndHours[] = $now->format("your_desire_format");
// Loop and add the next 7 dates
for($i = 0 ; $i < 7 ; $i++)
{
// Handle the delay between 11 am and 4 pm
// 11am -> 4pm = + 5h
// 4pm -> 11am = + 19h
if ($incementEvenOdd % 2 == 0)
$now->add(DateInterval::createFromDateString('5 hours'));
else
$now->add(DateInterval::createFromDateString('19 hours'));
// Appen the next value
$dayAndHours[] = $now->format("your_desire_format");
// Update increment
$incrementEvenOdd++;
}
请尝试下面的代码,我会存储在DB作为DATETIME:这取决于你根据你的需要来优化,它应该给你基本的逻辑思想:
<?php
$end_date = mktime(0, 0, 0, date("m") , date("d")+4, date("Y"));
$cnt = 0;
$day = 0;
$current_hour = date("H");
// To test with various values, uncomment below line and assign any hour
// $current_hour = "12";
if($current_hour < 11)
{
$day = 0;
$ts = mktime(11, 0, 0, date("m") , date("d"), date("Y"));
echo "<br>".date("Y-m-d H:i:s",$ts);
$ts = mktime(16, 0, 0, date("m") , date("d"), date("Y"));
echo "<br>".date("Y-m-d H:i:s",$ts);
$cnt = 2;
$day = $day + 1;
}
elseif($current_hour < 16)
{
$day = 0;
$ts = mktime(16, 0, 0, date("m") , date("d")+$day, date("Y"));
echo "<br>".date("Y-m-d H:i:s",$ts);
$cnt = 1;
$day = $day + 1;
}
elseif($current_hour >= 16)
{
$day = $day + 1;
}
while($cnt <= 8)
{
$ts = mktime(11, 0, 0, date("m") , date("d")+$day, date("Y"));
echo "<br>".date("Y-m-d H:i:s",$ts);
$cnt = $cnt + 1;
if($cnt >=8) break;
$ts = mktime(16, 0, 0, date("m") , date("d")+$day, date("Y"));
echo "<br>".date("Y-m-d H:i:s",$ts);
$cnt = $cnt + 1;
$day = $day + 1;
if($cnt >=8) break;
}
?>