我想显示给定年份的当前和前几个月,如下所示:
november-december 2019
september-october 2019
july-auguest 2019
may-june 2019
march-april 2019
january-february 2019
我当前的代码:
$start = $month = strtotime('2019-02-01');
$end = strtotime( date( 'Y-m-d' ) );
while($month < $end)
{
echo date('FY', $month);
echo '<br/>';
$month = strtotime("+1 month", $month);
}
您能告诉我该怎么做吗?目前正在显示一个月。
更新的代码:
$start = $month = strtotime('2019-01-01');
$end = strtotime( date( 'Y-m-d' ) );
while($month < $end) {
$current_prev_month = strtolower( date( 'F', $month ) . '-' . date( 'F', strtotime( '+1 month', $month ) ) . '-' . date( 'Y' ,$month ) );
$month = strtotime("+2 month", $month);
$current = get_term_by( 'slug', $current_prev_month, 'issues' );
if($current) {
break;
}
}
现在它可以完美显示,但是可以反转吗?
答案 0 :(得分:1)
在循环的每一遍中只需输出两个月:
$month = strtotime('2019-02-01');
$end = strtotime( date( 'Y-m-01' ) );
while ($month < $end) {
echo date('F-', $month);
$month = strtotime("+1 month", $month);
echo date('F Y', $month);
echo '<br/>';
$month = strtotime("+1 month", $month);
}
输出(截至5/2/20):
2019年2月-3月
2019年4月-5月
2019年6月-7月
2019年8月-9月
2019年10月-11月
2020年12月-1月
要向后输出日期,可以使用以下代码:
$end = strtotime('2019-02-01');
$month = strtotime( date( 'Y-m-01' ) );
while($month > $end)
{
$month = strtotime("-2 month", $month);
echo date('F-', $month);
echo date('F Y', strtotime("+1 month", $month));
echo '<br/>';
}
输出:
2020年12月-1月
2019年10月-11月
2019年8月-9月
2019年6月-7月
2019年4月-5月
2019年2月-3月
答案 1 :(得分:0)
尝试一下
$currentDate = new \DateTime();
$startDate = \DateTime::createFromFormat('Y-m-d', '2019-02-01');
while ($startDate->getTimestamp() < $currentDate->getTimestamp()) {
echo $currentDate->format('F-');
$currentDate->modify('-1 month');
echo $currentDate->format('F Y') . "<br/>\n";
$currentDate->modify('-1 month');
}