在 PHP 上打印其他两个日期之间的日期
Printing dates between two other dates on PHP
我正在尝试打印其他两个日期之间的日期。这是我的代码:
$begin = date("d/m/y");
$end = date("d/m/y", strtotime("+1 month"));
$i = 0;
while( strtotime($begin) <= strtotime($end) ){
echo "$begin\n";
$i++;
$begin = date("d/m/y", strtotime("+$i day") );
}
您可以在这里执行相同的代码:
http://sandbox.onlinephpfunctions.com/code/34c4b721553038f585806798121941bee0c66086
出于某种原因,此代码仅打印 25/01/2017 和 31/01/2017 之间的日期,而不是 25/01/2017 和 25/02/2017 之间的日期。我不知道出了什么问题。有人可以帮助我吗?
strtotime()
不支持 d/m/y
格式的日期。它将这些日期视为 m/d/y
.
要修复您的代码,请在前两行中使用 Y-m-d
格式。
旁注,我建议使用 \DateTime
类 来处理日期而不是字符串和整数。在这里阅读更多:https://paulund.co.uk/datetime-php
<?php
error_reporting(-1);
ini_set('display_errors', true);
$begin = new DateTime();
$end = (new DateTime())->modify('+1 month');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach ($period as $date) {
echo $date->format('d/m/y')."<br/>";
}
我正在尝试打印其他两个日期之间的日期。这是我的代码:
$begin = date("d/m/y");
$end = date("d/m/y", strtotime("+1 month"));
$i = 0;
while( strtotime($begin) <= strtotime($end) ){
echo "$begin\n";
$i++;
$begin = date("d/m/y", strtotime("+$i day") );
}
您可以在这里执行相同的代码: http://sandbox.onlinephpfunctions.com/code/34c4b721553038f585806798121941bee0c66086
出于某种原因,此代码仅打印 25/01/2017 和 31/01/2017 之间的日期,而不是 25/01/2017 和 25/02/2017 之间的日期。我不知道出了什么问题。有人可以帮助我吗?
strtotime()
不支持 d/m/y
格式的日期。它将这些日期视为 m/d/y
.
要修复您的代码,请在前两行中使用 Y-m-d
格式。
旁注,我建议使用 \DateTime
类 来处理日期而不是字符串和整数。在这里阅读更多:https://paulund.co.uk/datetime-php
<?php
error_reporting(-1);
ini_set('display_errors', true);
$begin = new DateTime();
$end = (new DateTime())->modify('+1 month');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach ($period as $date) {
echo $date->format('d/m/y')."<br/>";
}