我需要为我的用户提供一种方法,在未来的几天(包括今天)选择上午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()
类进行此操作?
答案 0 :(得分:0)
请尝试下面的代码,我将在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;
}
?>
答案 1 :(得分:0)
您只需要创建一个“现在”的日期时间,然后检查您是否在上午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++;
}
答案 2 :(得分:0)
<?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);