¿Cómo encontrar el último día del mes a partir de la fecha?


¿Cómo puedo obtener el último día del mes en PHP?

Dado:

$a_date = "2009-11-23"

Quiero 2009-11-30; y dado

$a_date = "2009-12-23"

Quiero 2009-12-31.

 302
Author: Foreever, 2009-11-06

23 answers

t devuelve el número de días en el mes de una fecha dada (ver los documentos para date):

$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));
 654
Author: Dominic Rodger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-06 10:36:15

El código que usa strtotime() fallará después del año 2038. (como se da en la primera respuesta en este hilo) Por ejemplo, intente usar lo siguiente:

$a_date = "2040-11-23";
echo date("Y-m-t", strtotime($a_date));

Dará respuesta como: 1970-01-31

Así que en lugar de strtotime, se debe usar la función DateTime. El siguiente código funcionará sin problema del año 2038:

$d = new DateTime( '2040-11-23' ); 
echo $d->format( 'Y-m-t' );
 91
Author: Mugunth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-01 01:51:03

Sé que esto es un poco tarde, pero creo que hay una forma más elegante de hacer esto con PHP 5.3+ usando la clase DateTime :

$date = new DateTime('now');
$date->modify('last day of this month');
echo $date->format('Y-m-d');
 77
Author: Hannoun Yassir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-20 22:12:14

También existe la función PHP incorporada cal_days_in_month()?

"Esta función devolverá el número de días en el mes del año para el calendario especificado." http://php.net/manual/en/function.cal-days-in-month .

echo cal_days_in_month(CAL_GREGORIAN, 11, 2009); 
// = 30
 59
Author: MPV,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-07 11:43:16

Esto debería funcionar:

$week_start = strtotime('last Sunday', time());
$week_end = strtotime('next Sunday', time());

$month_start = strtotime('first day of this month', time());
$month_end = strtotime('last day of this month', time());

$year_start = strtotime('first day of January', time());
$year_end = strtotime('last day of December', time());

echo date('D, M jS Y', $week_start).'<br/>';
echo date('D, M jS Y', $week_end).'<br/>';

echo date('D, M jS Y', $month_start).'<br/>';
echo date('D, M jS Y', $month_end).'<br/>';

echo date('D, M jS Y', $year_start).'<br/>';
echo date('D, M jS Y', $year_end).'<br/>';
 23
Author: kaleazy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-19 22:35:38

Puede crear una fecha para el primer día del mes siguiente, y luego usar strtotime("-1 day", $firstOfNextMonth)

 17
Author: nikc.org,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-06 10:36:40

Lo que está mal - Lo más elegante para mí es usar DateTime

Me pregunto si no veo DateTime::createFromFormat, one-liner

$lastDay = \DateTime::createFromFormat("Y-m-d", "2009-11-23")->format("Y-m-t");
 12
Author: john Smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-30 08:21:30

Su solución está aquí..

$lastday = date('t',strtotime('today'));
 9
Author: Vineet Kadkol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-06 04:47:07

Pruebe esto, si está utilizando PHP 5.3+,

$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');

Para encontrar la última fecha del próximo mes, modifíquese de la siguiente manera,

 $date->modify('last day of 1 month');
 echo $date->format('Y-m-d');

Y así sucesivamente..

 9
Author: Mohammed Safeer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-12 06:02:51

Si utiliza la extensión API Carbon para PHP DateTime, puede obtener el último día del mes con:

$date = Carbon::now();
$date->addMonth();
$date->day = 0;
echo $date->toDateString(); // use toDateTimeString() to get date and time 
 7
Author: eaykin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-29 11:05:22

También se puede utilizar con datetime

$date = new \DateTime();
$nbrDay = $date->format('t');
$lastDay = $date->format('Y-m-t');
 4
Author: Ajouve,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-01 13:48:09

Puedes encontrar el último día del mes de varias maneras. Pero simplemente puede hacer esto usando PHP strtotime () y date () función.Me imagino que su código final se vería algo como esto:

$a_date = "2009-11-23";
echo date('Y-m-t',strtotime($a_date));

Demostración En Vivo

Pero si está utilizando PHP >= 5.2 le sugiero encarecidamente que utilice el nuevo objeto DateTime. Por ejemplo, como a continuación:

$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');

Demostración En Vivo

También, puede resolver esto usando su propia función como a continuación:

/**
 * Last date of a month of a year
 *
 * @param[in] $date - Integer. Default = Current Month
 *
 * @return Last date of the month and year in yyyy-mm-dd format
 */
function last_day_of_the_month($date = '')
{
    $month  = date('m', strtotime($date));
    $year   = date('Y', strtotime($date));
    $result = strtotime("{$year}-{$month}-01");
    $result = strtotime('-1 second', strtotime('+1 month', $result));

    return date('Y-m-d', $result);
}

$a_date = "2009-11-23";
echo last_day_of_the_month($a_date);
 4
Author: Faisal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-11 03:54:27
$date1 = $year.'-'.$month; 
$d = date_create_from_format('Y-m',$date1); 
$last_day = date_format($d, 't');
 2
Author: kayla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-16 01:04:11

Aquí está una función completa:

public function get_number_of_days_in_month($month, $year) {
    // Using first day of the month, it doesn't really matter
    $date = $year."-".$month."-1";
    return date("t", strtotime($date));
}

Esto produciría lo siguiente:

echo get_number_of_days_in_month(2,2014);

Salida: 28

 1
Author: Firze,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-20 08:17:24

Hay maneras de obtener el último día del mes.

//to get last day of current month
echo date("t", strtotime('now'));

//to get last day from specific date
$date = "2014-07-24";
echo date("t", strtotime($date));

//to get last day from specific date by calendar
$date = "2014-07-24";
$dateArr=explode('-',$date);
echo cal_days_in_month(CAL_GREGORIAN, $dateArr[1], $dateArr[0]); 
 1
Author: vineet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-24 05:36:12

Usando Zend_Date es bastante fácil:

$date->setDay($date->get(Zend_Date::MONTH_DAYS));
 1
Author: mkerstner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-03 14:55:46

Llego tarde, pero hay un puñado de maneras fáciles de hacer esto como se mencionó:

$days = date("t");
$days = cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'));
$days = date("j",mktime (date("H"),date("i"),date("s"),(date("n")+1),0,date("Y")));

Usar mktime() es mi opción para un control completo sobre todos los aspectos del tiempo... I. E.

echo "<br> ".date("Y-n-j",mktime (date("H"),date("i"),date("s"),(11+1),0,2009));

Establecer el día en 0 y mover su mes hacia arriba 1 le dará el último día del mes anterior. 0 y los números negativos tienen el efecto similar en los diferentes argumentos. PHP: mktime-Manual

Como algunos han dicho strtotime no es el camino más sólido a seguir y poco si ninguno es tan fácilmente versátil.

 1
Author: JSG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-09 17:26:00
function first_last_day($string, $first_last, $format) {
    $result = strtotime($string);
    $year = date('Y',$result);
    $month = date('m',$result);
    $result = strtotime("{$year}-{$month}-01");
    if ($first_last == 'last'){$result = strtotime('-1 second', strtotime('+1 month', $result)); }
    if ($format == 'unix'){return $result; }
    if ($format == 'standard'){return date('Y-m-d', $result); }
}

Http://zkinformer.com/?p=134

 0
Author: Kevin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-01 00:02:58

Lo he envuelto en mi clase auxiliar de fecha y hora aquí https://github.com/normandqq/Date-Time-Helper utilizar $dateLastDay = Model_DTHpr::getLastDayOfTheMonth();

Y se hace

 0
Author: Norman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-25 01:20:06

Otra forma de usar mktime y no date('t') :

$dateStart= date("Y-m-d", mktime(0, 0, 0, 10, 1, 2016)); //2016-10-01
$dateEnd = date("Y-m-d", mktime(0, 0, 0, 11, 0, 2016)); //This will return the last day of october, 2016-10-31 :)

Así que de esta manera calcula si es 31,30 o 29

 0
Author: Robin Rumeau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-08 09:02:32

Carbon Extensión de API para PHP DateTime

Carbon::parse("2009-11-23")->lastOfMonth()->day;

O

Carbon::createFromDate(2009, 11, 23)->lastOfMonth()->day;

Se retrun

30
 0
Author: josef,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-17 07:59:04

Esta es una forma mucho más elegante de llegar al final del mes:

  $thedate = Date('m/d/Y'); 
  $lastDayOfMOnth = date('d', mktime(0,0,0, date('m', strtotime($thedate))+1, 0, date('Y', strtotime($thedate)))); 
 -2
Author: Louis Sterio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-30 16:59:53

Puede usar "t" en la función de fecha para obtener el número de días en un mes en particular.

El código será algo así:

function lastDateOfMonth($Month, $Year=-1) {
    if ($Year < 0) $Year = 0+date("Y");
    $aMonth         = mktime(0, 0, 0, $Month, 1, $Year);
    $NumOfDay       = 0+date("t", $aMonth);
    $LastDayOfMonth = mktime(0, 0, 0, $Month, $NumOfDay, $Year);
    return $LastDayOfMonth;
}

for($Month = 1; $Month <= 12; $Month++)
    echo date("Y-n-j", lastDateOfMonth($Month))."\n";

El código se explica por sí mismo. Así que espero que ayude.

 -3
Author: NawaMan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-06 10:39:23