简体   繁体   中英

php get date from now every 1 year between two dates

I'm trying to get the date every 1 year or any variable interval between two dates. My dates examples are as follows. It just seems to run forever and I cant make it work and it doesn't print anything out at the end.

$currentDate = '2014-04-15';
$endDate = '2018-04-15';
$reminder = '+1 year';

 $dateArray = array();

    while($currentDate <= $endDate){
        $currentDate = date('Y-m-d', strtotime($reminder, strtotime($currentDate)));
    array_push($dateArray, $currentDate);
    }
    print_r($dateArray);

please change

$dateArray = array_push($dateArray, $currentDate);

to

array_push($dateArray, $currentDate);

Because array_push, returns boolean and next time, you call this function, it tries to store string in the int/boolean type and cause error.

You can use the DateInterval class and DateTime::Add() method:

    $begin_date = DateTime::createFromFormat('Y-m-d', '2014-04-15');
    $end_date = DateTime::createFromFormat('Y-m-d', '2018-04-15');

    $res_array = array();

    while ($begin_date < $end_date)
    {
        $begin_date->Add(DateInterval::createFromDateString('1 year'));
        $res_array[] = clone($begin_date);
    }
    echo ("<pre>"); print_r($res_array); echo ("</pre>");

Thats the Object oriented style.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM