PHP如何跳转到下个月的日期?

时间:2013-11-20 20:28:49

标签: php

我有一个问题,我不能跳到下个月,我尝试通过包含IF但它不起作用,我不明白为什么。例如,如果我有两个日期,则必须打印从第一个日期到下一个日期的所有日期,但是打印天数不是31,而是直到100,然后再从1到100开始,月份不会更改。

我试图包含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";

2 个答案:

答案 0 :(得分:1)

查看DateTime::addDateInterval。你可以这样做:

$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');

因此,使用它可以精确地对DateTime对象执行数学运算,然后最终以您想要的任何格式将其吐出。

答案 1 :(得分:0)

如果你想跳到下个月试试这个:

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

查看strtotime

相关问题