1

我正在尝试一次使用 PHP 和 MySQL(仅在工作日)插入频繁的工作时间。

从 : 01.02.2013 08:30
到 : 28.02.2013 17:30

然后它应该插入每个工作日直到 28.02.2013 这样

01.02.2013 08:30 -01.02.2013 17:30
02.02.2013 08:30 -02.02.2013 17:30
03.02.2013 08:30 -03.02.2013 17:30
...

您能否提供一些从哪里开始的提示?

我用下面的代码只插入一个日期..

$startDate = $rsnew["starttime"];  
$endDate =  $rsnew["endtime"];      

// Convert to UNIX timestamps                          
$currentTime = strtotime($startDate);
$endTime = strtotime($endDate);

// Loop until we reach the last day
$result = array();                          
while ($currentTime <= $endTime) {
    if (date('N', $currentTime) < 6) {
        $result[] = date('Y-m-d', $currentTime);
    }
    $currentTime = strtotime('+1 day', $currentTime);
    echo "Hallo" .$currentTime;   
}  

// start insertion        
foreach($result as $value)        
{
    $MyResult = ew_Execute("INSERT INTO dates (date) VALUES ('".$value."')");
    echo "Hallo" .$value;                                                         
}                          
4

1 回答 1

0

你可能不再需要这个了,但这里有一个简单的方法,它也非常有效:

$start    = new DateTime('2013-02-01');
$finish   = (new DateTime('2013-02-28'))->add(new DateInterval('P1D'));
$interval = new DateInterval('P1D');
$period   = new DatePeriod($start, $interval, $finish);
$dates    = array();

foreach ($period as $dt) {
    $dates[] = $dt->format('Y-m-d');
}

$MyResult = ew_Execute("INSERT INTO dates (date) VALUES ('" . implode("'),('", $dates) . "')");

这是这样做的:

  1. 为我们的开始日期和结束日期创建DateTime对象(我们必须在结束日期上添加一天,因为我们在下面创建的循环不包括最后一天)。
  2. 创建一个DateInterval对象,该对象表示当我们循环遍历它们(1 天)时我们希望将 DateTimes 增加多少。
  3. 创建一个DatePeriod对象,它允许我们遍历我们想要的日期。
  4. 创建一个空数组来存储我们稍后将添加到数据库中的日期。
  5. 遍历开始日期和结束日期之间的日期,将日期添加到我们的数组中。
  6. 用于implode()创建一个查询,而不是 [ num days ] 个查询,执行起来更快。
于 2014-01-07T02:21:33.523 回答