I want to increment a date , let's say today :
$today = date("Y-m-d")
, by 3 months during 3 years.
Example :
2014-09-19
-> incremented by 3 months becomes 2014-12-19
-> incremented by 3 months becomes 2015-02-19
and so on until my date it's smaller or equal with 3 years from that date , in our example 2017-09-19
.
<?php
//using DatePeriod
$begin = new DateTime('2014-09-16'); // set the starting date
$end = new DateTime('2017-09-16'); // set the ending date
$interval = new DateInterval('P3M'); // 3 months interval
$range = new DatePeriod($begin, $interval, $end); // set the period
foreach($range as $date) {
// so foreach three months, this will loop until the end date
echo $date->format('Y-m-d') . '<br/>';
}
?>
The output will be:
2014-09-19
2014-12-19
2015-03-19
2015-06-19
2015-09-19
2015-12-19
2016-03-19
2016-06-19
2016-09-19
2016-12-19
2017-03-19
2017-06-19
<?php
//another way
$today = new DateTime('2014-09-19');
$formatted = $today->modify("+3 months");
echo $formatted->format('Y-m-d');
?>
<?php
//another way
$startDate = date("Y-m-d");
$endDate = date('Y-m-d', strtotime("+3 years", strtotime($startDate )));
echo $startDate."<br/>";
while(strtotime($startDate) < strtotime($endDate) ){
$startDate = date('Y-m-d', strtotime("+3 months", strtotime($startDate )));
echo $startDate."<br/>";
}
?>
0 comments:
Post a Comment