質問

I want to get the date between two dates excluding last date, following code i will used to find dates. But it trigger an error saying:

Class 'DateInterval' not found

Code:

$start = new DateTime('2014-08-06');
$end = new DateTime('2014-09-06');
$oneday = new DateInterval("P1D");

$days = array();
$data = "7.5";

foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
    $day_num = $day->format("N");

    if($day_num < 6) { 
        $days[$day->format("Y-m-d")] = $data;
    } 
} 

print_r($days);
役に立ちましたか?

解決

Looks like your version of php doesn't have the DateInterval class. Here is an alternative using strtotime():

$start = '2014-08-06';
$end = '2014-09-06';

$num_days = floor((strtotime($end)-strtotime($start))/(60*60*24));
$data = '7.5';

$days = array();

for ($i=0; $i<$num_days; $i++) 
    if (date('N', strtotime($start . "+ $i days")) < 6)
        $days[date('Y-m-d', strtotime($start . "+ $i days"))] = $data;

print_r($days);

Result:

Array
(
    [2014-08-06] => 7.5
    [2014-08-07] => 7.5
    [2014-08-08] => 7.5
    [2014-08-11] => 7.5
    [2014-08-12] => 7.5
    [2014-08-13] => 7.5
    [2014-08-14] => 7.5
    [2014-08-15] => 7.5
    [2014-08-18] => 7.5
    [2014-08-19] => 7.5
    [2014-08-20] => 7.5
    [2014-08-21] => 7.5
    [2014-08-22] => 7.5
    [2014-08-25] => 7.5
    [2014-08-26] => 7.5
    [2014-08-27] => 7.5
    [2014-08-28] => 7.5
    [2014-08-29] => 7.5
    [2014-09-01] => 7.5
    [2014-09-02] => 7.5
    [2014-09-03] => 7.5
    [2014-09-04] => 7.5
    [2014-09-05] => 7.5
)

他のヒント

PHP's DateInterval class was introduced in PHP version 5.3.0, so if you're using a lower version of PHP, you will get the error saying that it doesn't know about that class.

If you are indeed using a PHP version lower than 5.3.0, I would strongly advice you to upgrade your PHP version.

try

$begin = new DateTime('2014-08-06');
$end = new DateTime('2014-09-06');
$end = $end->modify( '+1 day' ); 
$days = array();
$data = "7.5";
    while($begin < $end) {
        $day_num = $begin->format("N"); 
            if($day_num < 6) { 
                   $days[$begin->format("Y-m-d")] = $data;
            } 
            $begin->modify('+1 day');
    }
print_r($days);

//output :-

Array
(
    [2014-08-06] => 7.5
    [2014-08-07] => 7.5
    [2014-08-08] => 7.5
    [2014-08-11] => 7.5
    [2014-08-12] => 7.5
    [2014-08-13] => 7.5
    [2014-08-14] => 7.5
    [2014-08-15] => 7.5
    [2014-08-18] => 7.5
    [2014-08-19] => 7.5
    [2014-08-20] => 7.5
    [2014-08-21] => 7.5
    [2014-08-22] => 7.5
    [2014-08-25] => 7.5
    [2014-08-26] => 7.5
    [2014-08-27] => 7.5
    [2014-08-28] => 7.5
    [2014-08-29] => 7.5
    [2014-09-01] => 7.5
    [2014-09-02] => 7.5
    [2014-09-03] => 7.5
    [2014-09-04] => 7.5
    [2014-09-05] => 7.5
)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top