PHP中有没有办法以下列格式获取当前和之前的5个月?
April 2014
March 2014
February 2014
January 2014
December 2013
November 2013
答案 0 :(得分:12)
您是否尝试过以下操作:
<?php
echo date('F, Y');
for ($i = 1; $i < 6; $i++) {
echo date(', F Y', strtotime("-$i month"));
}
如果这不起作用,请告诉我。
答案 1 :(得分:3)
试试这个
for ($j = 0; $j <= 5; $j++) {
echo date("F Y", strtotime(" -$j month"));
}
答案 2 :(得分:2)
for( $i = 0; $i <= 5 ; $i++) {
print date("F Y", strtotime("-".$i." month"))."\n";
}
实现日期的另一种格式外观PHP日期格式HERE
答案 3 :(得分:1)
为什么不将DateTime对象用作
$start = new DateTime('first day of this month - 6 months');
$end = new DateTime('last month');
$interval = new DateInterval('P1M'); // http://www.php.net/manual/en/class.dateinterval.php
$date_period = new DatePeriod($start, $interval, $end);
$months = array();
foreach($date_period as $dates) {
array_push($months, $dates->format('F').' '.$dates->format('Y'));
}
print_r($months);
答案 4 :(得分:1)
<?php
for ($i =0; $i < 6; $i++) {
$months[] = date("F Y", strtotime( date( 'Y-m-01' )." -$i months"));
}
print_r($months)
?>
试试这个..
答案 5 :(得分:1)
不要使用:
<?php
for ($i = 0; $i <= 6; $i++) {
echo date('F Y', strtotime(-$i . 'month'));
}
// With date e.g.: "May, 31", outputs:
// May, 2018, May 2018, March 2018, March 2018, January 2018, December 2017
你可以通过以下方式修复它:
<?php
for ($i = 0; $i <= 6; $i++) {
echo date('F Y', strtotime('last day of ' . -$i . 'month'));
}
或者更好地使用DateTime,例如:
$dateTime = new DateTime('first day of this month');
for ($i = 1; $i <= 6; $i++) {
echo $dateTime->format('F Y');
$dateTime->modify('-1 month');
}
答案 6 :(得分:0)
for ($i = 1; $i <= 6; $i++) {
$months[] = date("M-y", strtotime( date( 'Y-m-01' )." -$i months"));
}
print_r($months);
答案 7 :(得分:0)
@php
for($i=0; $i<=5; $i++) {
$last_six_months[] =date("Y-m-d", strtotime( date( 'Y-m-01' )." -$i months"));
}
$last_six_months = array_reverse($last_six_months); // If you want to reverse...
@endphp
next >>>
@foreach($last_six_months as $key => $row)
<span>{{date('F Y',strtotime($row))}}</span>
@endforeach