![](/img/trans.png)
[英]Previous Month, Next Month and Month ,Year are not working in Calendar PHP
[英]Month and Year not working in PHP
我想獲取下一個18個月的月份和年份。 我嘗試了以下代碼:
$dat=strtotime(date('Y-m-d'));
$mnth = date('n');
$yr=date('Y');
echo $mnth." | " . $yr . " | " . date("Y-m-d", $dat);
echo "<hr>";
for($i=0; $i<=18;$i++)
{
echo date("n", strtotime("+1 month", $dat)) ." | ".date("Y", strtotime("+1 month", $dat)) . " | " . date("Y-m-d", strtotime("+1 month", $dat)) ."<br><hr>";
$dat=date("Y-m-d", strtotime("+1 month", $dat));
}
迭代和第一次迭代之前的代碼可以正常工作,如下所示:
8 | 2018 | 2018-08-28
9 | 2018 | 2018-09-28
但是所有后續迭代都給出以下錯誤:
注意:第11行的D:\\ Programs \\ PHP \\ aa \\ tdate.php中遇到的格式不正確的數值
注意:第11行的D:\\ Programs \\ PHP \\ aa \\ tdate.php中遇到的格式不正確的數值
注意:第11行的D:\\ Programs \\ PHP \\ aa \\ tdate.php中遇到一個格式不正確的數值| 1970年| 1970-02-01
請提出一些解決方案。
當您嘗試使用date()
和strtotime()
操縱日期時,您將以它們並非真正為它們設計的方式使用它們。
通過將DateTime()
與DateInterval()
和DatePeriod()
使用,可以快速,輕松, 清晰地迭代日期。
$start = new \DateTime('first day of this month');
$end = (new \DateTime('first day of this month'))->modify('+18 months');
$interval = new \DateInterval('P1M');
$period = new \DatePeriod($start, $interval, $end);
foreach ($period as $month) {
$lastDayOfMonth = $month->format('t');
$day = (date('d') > $lastDayOfMonth) ? $lastDayOfMonth : date('d');
echo $month->format("n | Y | Y-m-{$day}");
echo "\n";
}
注意事項:
我建議使用DateTime
類來完成此操作,這會容易得多:
// The actual month
$date = new DateTime(date('Y-m-') . '1');
// For the next 18 months
for ($i=0; $i < 18; $i++) {
// Add a month to the date
$date->add(new DateInterval('P1M'));
// Output it as you wish:
echo $date->format('n | Y | Y-m-d') . '<br>';
}
$dat=strtotime(date('Y-m-d'));
for($i=0; $i<=18;$i++)
{
echo date("n", strtotime("+".$i." month", $dat)) ." | ".date("Y", strtotime("+".$i." month", $dat)) . " | " . date("Y-m-d", strtotime("+".$i." month", $dat)) ."<br><hr>";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.