Gerda
Gerda

Reputation: 3

PHP how to jump to next month in date?

I have a problem, I can't jump to the next month, I try to do it by including IF but it does not work and I don't understand why. For example if I have two dates, it must print all dates from first date to next date, but it is printing days not till 31, but till 100 and then again starts from 1 till 100, and month does not changes.

I have tried to include if:

for ($k=$newformat;$k<$newformat2;$k++) // $newformat is first date from file, $newformat2 is second date, k is year, kk is month, kkk is day
{
$diena = $month = date("d",strtotime($k)); // $diena is day
$menesis = $month = date("m",strtotime($k)); // $menesis is month
$metai = date("Y",strtotime($k)); // $metai is year

if ($diena>31)
{
$diena=1;
$menesis=$menesis + 1;
}

if ($menesis>12)
{
$menesis=1;
$metai=$metai + 1;
}

//down here I'm checking are these dates are between my two dates, if it are, then $kiekis++ and it must print $kiekis
if($menesis = date("m",strtotime($k)) == 1 &&  $diena = date("d",strtotime($k)) == 1 || $menesis2 = date("m",strtotime($k)) == 2 &&  $diena2 = date("d",strtotime($k)) == 16 || $menesis3 = date("m",strtotime($k)) == 3 &&  $diena3 = date("d",strtotime($k)) == 11)
$kiekis++;

}

echo "Kiekis: $kiekis";

Upvotes: 0

Views: 341

Answers (2)

Thomas
Thomas

Reputation: 417

If you want to jump to next month try this :

<?php
$myDate = date('d-m-y');
echo date('d-m-Y', strtotime("+1 month $myDate"));
?>

Have a look at strtotime

Upvotes: 0

jszobody
jszobody

Reputation: 28911

Take a look at DateTime::add and DateInterval. You can do things like this:

$date = new DateTime($k); // Assuming $k is a valid date format already
$date->add(new DateInterval('P1M')); // Adds 1 month
echo $date->format('Y-m-d');

So using this you can precisely perform mathematical operations on a DateTime object, and then finally spit it out in whatever format you want.

Upvotes: 1

Related Questions