如何获得上个月和下个月?

时间:2010-10-14 06:57:28

标签: php date

$year  = 2010;
$month = 10;

如何获取上个月2010-09和下个月2010-11

8 个答案:

答案 0 :(得分:18)

$date = mktime( 0, 0, 0, $month, 1, $year );
echo strftime( '%B %Y', strtotime( '+1 month', $date ) );
echo strftime( '%B %Y', strtotime( '-1 month', $date ) );

答案 1 :(得分:3)

尝试这样:

$date = mktime(0, 0, 0, $month, 1, $year);
echo date("Y-m", strtotime('-1 month', $date));
echo date("Y-m", strtotime('+1 month', $date));

或更短,如下:

echo date("Y-m", mktime(0, 0, 0, $month-1, 1, $year));
echo date("Y-m", mktime(0, 0, 0, $month+1, 1, $year));

答案 2 :(得分:2)

PHP在这方面很棒,它会通过纠正你的日期来处理日期溢出......

$PreviousMonth = mktime(0, 0, 0, $month - 1, 1, $year);
$CurrentMonth = mktime(0, 0, 0, $month, 1, $year);
$NextMonth = mktime(0, 0, 0, $month + 1, 1, $year);

echo '<p>Next month is ' . date('Ym', $NextMonth) . 
    ' and previous month is ' . date('Ym', $PreviousMonth . '</p>';

答案 3 :(得分:1)

$prevMonth = $month - 1;
$nextMonth = $month + 1;
$prevYear = $year;
$nextYear = $year;

if ($prevMonth < 1) {
    $prevMonth = 1;
    $prevYear -= 1;
}

if ($nextMonth > 12) {
    $nextMonth = 1;
    $nextYear += 1
}

// PHP > 5.2.0
$date = new DateTime();
$date->setDate($year, $month, 1);
$prevDate = $date->modify('-1 month');
$nextDate = $date->modify('+1 month');
// some $prevDate->format() and $nextDate->format() 

答案 4 :(得分:1)

您只需将1添加到当月,然后查看您是否越过了这一年:

$next_year  = $year;
$next_month = ++$month;

if($next_month == 13) {
  $next_month = 1;    
  $next_year++;
}

与上个月类似,您可以这样做:

$prev_year  = $year;
$prev_month = --$month;

if($prev_month == 0) {
  $prev_month = 12;
  $prev_year--;
}

答案 5 :(得分:0)

strftime * : - *根据区域设置格式化时间和/或日期。月份和工作日名称以及其他依赖于语言的字符串遵循使用setlocale()设置的当前语言环境。

strftime( '%B %Y', strtotime( '+1 month', $date ) );
strftime( '%B %Y', strtotime( '-1 month', $date ) );

答案 6 :(得分:0)

     echo date('Y-m-d', strtotime('next month'));

答案 7 :(得分:0)

 setlocale(LC_TIME,"turkish");
 $Currentmonth=iconv("ISO-8859-9","UTF-8",strftime('%B'));
 $Previousmonth=iconv("ISO-8859-9","UTF-8",strftime('%B',strtotime('-1 MONTH')));
 $Nextmonth=iconv("ISO-8859-9","UTF-8",strftime('%B',strtotime('+1 MONTH')));

echo $Previousmonth; // Şubat /* 2017-02 */
echo $Currentmonth; // Mart /* 2017-03 */
echo $Nextmonth; // Nisan /* 2017-04 */