¿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.
¿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.
Respuestas:
tdevuelve el número de días en el mes de una fecha determinada (consulte los documentos paradate ):
$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));
DateTimeusted puede hacer algo como esto:(new DateTime('2009-11-23'))->modify('last day of')
El código que usa strtotime () fallará después del año 2038. (como se indica 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
Entonces, en lugar de strtotime, se debe usar la función DateTime. El siguiente código funcionará sin el problema del año 2038:
$d = new DateTime( '2040-11-23' );
echo $d->format( 'Y-m-t' );
strtotimecódigo me da este resultado: 2040-11-30
Sé que esto es un poco tarde, pero creo que hay una manera más elegante de hacerlo PHP 5.3+usando la clase DateTime :
$date = new DateTime('now');
$date->modify('last day of this month');
echo $date->format('Y-m-d');
$date = DateTime::createFromFormat('m/d/Y', '1/10/2014');
También existe la función PHP integrada cal_days_in_month () ?
"Esta función devolverá la cantidad 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
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/>';
Lo que está mal: lo más elegante para mí es usar DateTime
Me pregunto si no veo DateTime::createFromFormat, una línea
$lastDay = \DateTime::createFromFormat("Y-m-d", "2009-11-23")->format("Y-m-t");
Puede crear una fecha para el primero del próximo mes y luego usar strtotime("-1 day", $firstOfNextMonth)
mktime(0, 0, 0, $month+1, 0, $year);
strtotime()y mktime()se desalienta bec. de errores conocidos, como la determinación de la fecha al borde de los meses y los cálculos del año bisiesto. Como DateTimeestá disponible, debe usar esta clase para evitar problemas en el futuro. Como dije muchas veces antes que yo, ambos funcionan strtotime()y mktime()fallarán después de 2038. Por eso voté en contra ...
Intente 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, modifique de la siguiente manera,
$date->modify('last day of 1 month');
echo $date->format('Y-m-d');
y así..
Tu solución está aquí ...
$lastday = date('t',strtotime('today'));
31para lo Septemberque, como saben, eso no es correcto.
Puede encontrar el último día del mes de varias maneras. Pero simplemente puede hacer esto usando PHP strtotime () y la función date () . Me imagino que su código final se vería así:
$a_date = "2009-11-23";
echo date('Y-m-t',strtotime($a_date));
Pero si está utilizando PHP> = 5.2, le sugiero que use 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');
Además, 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);
Si utiliza la extensión Carbon API 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
$date->day = 0;
Si tiene un mes sabio, obtenga la última fecha del mes, entonces,
public function getLastDateOfMonth($month)
{
$date = date('Y').'-'.$month.'-01'; //make date of month
return date('t', strtotime($date));
}
$this->getLastDateOfMonth(01); //31
Aquí hay 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 generaría lo siguiente:
echo get_number_of_days_in_month(2,2014);
Salida: 28
Hay formas 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]);
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 objetivo para tener un control completo sobre todos los aspectos del tiempo ... IE
echo "<br> ".date("Y-n-j",mktime (date("H"),date("i"),date("s"),(11+1),0,2009));
Establecer el día en 0 y subir el mes 1 le dará el último día del mes anterior. El 0 y los números negativos tienen el mismo efecto en los diferentes argumentos. PHP: mktime - Manual
Como algunos han dicho, el tiempo de ejecución no es el camino más sólido y poco o nada es tan versátil.
Estoy usando strtotime con cal_days_in_month de la siguiente manera:
$date_at_last_of_month=date('Y-m-d', strtotime('2020-4-1
+'.(cal_days_in_month(CAL_GREGORIAN,4,2020)-1).' day'));
Lo he incluido en mi clase de ayuda de fecha y hora aquí
https://github.com/normandqq/Date-Time-Helper
usando
$dateLastDay = Model_DTHpr::getLastDayOfTheMonth();
Y esta hecho
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 :)
De esta manera, calcula si son 31,30 o 29
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); }
}
Esta es una forma mucho más elegante de llegar a fin de mes:
$thedate = Date('m/d/Y');
$lastDayOfMOnth = date('d', mktime(0,0,0, date('m', strtotime($thedate))+1, 0, date('Y', strtotime($thedate))));
Puede usar " t" en la función de fecha para obtener la cantidad de días en un mes en particular.
El código será algo como esto:
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.