2010-10-14 17 views

Respuesta

17
$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
$prevMonth = $month - 1; 
$nextMonth = $month + 1; 
$prevYear = $year; 
$nextYear = $year; 

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

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

o

// 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() 
+1

PHP hace todo este trabajo duro para usted con mktime. – Fenton

+0

@Sohnee, prefiero DateTime –

+0

@RS - No tengo problemas con su ejemplo 5.2 ... es el anterior. – Fenton

1

Usted puede añadir 1 para el mes en curso y luego ver si usted cruzó el año:

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

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

mismo modo para el mes anterior se puede hacer :

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

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

¡Crikey! ¿Sabías que PHP puede hacer esto por ti? – Fenton

+0

Lo sé. Pero este es más claro. Al menos para mi. – codaddict

2

PHP es impresionante en este sentido, que se encargará de los desbordamientos de fecha mediante la corrección de la fecha para usted ...

$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>'; 
0

strftime * : - * Formato de la hora y/o fecha de acuerdo con la configuración regional. Los nombres de mes y día de la semana y otras cadenas dependientes del idioma respetan la configuración regional actual establecida con setlocale().

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

tratan de esta manera:

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

o, más corto, como este:

echo date("Y-m", mktime(0, 0, 0, $month-1, 1, $year)); 
echo date("Y-m", mktime(0, 0, 0, $month+1, 1, $year)); 
0
 echo date('Y-m-d', strtotime('next month')); 
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 */ 
Cuestiones relacionadas