簡體   English   中英

月和年不適用於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";
}

演示版

注意事項:

  1. 確保您以每月的第一天作為開始日期,就好像您使用的代碼將有31天的月份會中斷,並且從每個月的29日到該月底的2月都是一個問題。
  2. 如果當前日期在另一個月的最后一天之后,則需要返回到該月的最后一天。 從29日開始,這將在每個月有31天和每月2月的月份中發揮作用。

我建議使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM