Come posso ottenere l'ultimo giorno del mese in PHP?
Dato:
$a_date = "2009-11-23"
Voglio il 30/11/2009; e dato
$a_date = "2009-12-23"
Voglio il 2009-12-31.
Come posso ottenere l'ultimo giorno del mese in PHP?
Dato:
$a_date = "2009-11-23"
Voglio il 30/11/2009; e dato
$a_date = "2009-12-23"
Voglio il 2009-12-31.
Risposte:
trestituisce il numero di giorni nel mese di una determinata data (consultare la documentazione perdate ):
$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));
DateTimete puoi fare qualcosa del genere:(new DateTime('2009-11-23'))->modify('last day of')
Il codice che utilizza strtotime () avrà esito negativo dopo l'anno 2038. (come indicato nella prima risposta in questo thread) Ad esempio, provare a utilizzare quanto segue:
$a_date = "2040-11-23";
echo date("Y-m-t", strtotime($a_date));
Darà risposta come: 1970-01-31
Quindi, invece di strtotime, dovrebbe essere usata la funzione DateTime. Il seguente codice funzionerà senza il problema dell'anno 2038:
$d = new DateTime( '2040-11-23' );
echo $d->format( 'Y-m-t' );
strtotimecodice mi dà questo risultato: 2040-11-30
So che è un po 'tardi, ma penso che ci sia un modo più elegante di farlo PHP 5.3+usando la classe 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');
Esiste anche la funzione PHP integrata cal_days_in_month () ?
"Questa funzione restituirà il numero di giorni nel mese dell'anno per il calendario specificato." http://php.net/manual/en/function.cal-days-in-month .
echo cal_days_in_month(CAL_GREGORIAN, 11, 2009);
// = 30
Questo dovrebbe funzionare:
$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/>';
Cosa c'è di sbagliato - Il più elegante per me sta usando DateTime
Mi chiedo di non vedere DateTime::createFromFormat, one-liner
$lastDay = \DateTime::createFromFormat("Y-m-d", "2009-11-23")->format("Y-m-t");
È possibile creare una data per il primo del mese successivo e quindi utilizzare strtotime("-1 day", $firstOfNextMonth)
mktime(0, 0, 0, $month+1, 0, $year);
strtotime()ed mktime()è sconsigliato bec. di bug noti come la determinazione della data al limite dei mesi e le calaculazioni dell'anno bisestile. Poiché DateTimeè disponibile, è necessario utilizzare questa classe per evitare problemi in futuro. Come ho detto molte volte prima di me, entrambe funzionano strtotime()e mktime()falliranno dopo il 2038. Ecco perché ho effettuato il downvoting ...
Prova questo, se stai usando 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');
Per trovare la data dell'ultimo mese successivo, modificare come segue,
$date->modify('last day of 1 month');
echo $date->format('Y-m-d');
e così via..
La tua soluzione è qui ..
$lastday = date('t',strtotime('today'));
31per Septembercui, come sapete, non è corretto.
Puoi trovare l'ultimo giorno del mese in diversi modi. Ma semplicemente puoi farlo usando PHP strtotime () e la funzione date (). Immagino che il tuo codice finale sarebbe simile a questo:
$a_date = "2009-11-23";
echo date('Y-m-t',strtotime($a_date));
Ma se stai usando PHP> = 5.2 ti consiglio vivamente di usare il nuovo oggetto DateTime. Ad esempio come di seguito:
$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');
Inoltre, puoi risolverlo usando la tua funzione come di seguito:
/**
* 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);
Se usi l' estensione Carbon API per PHP DateTime, puoi ottenere l'ultimo giorno del mese con:
$date = Carbon::now();
$date->addMonth();
$date->day = 0;
echo $date->toDateString(); // use toDateTimeString() to get date and time
$date->day = 0;
Se hai un mese, ottieni l'ultima data del mese,
public function getLastDateOfMonth($month)
{
$date = date('Y').'-'.$month.'-01'; //make date of month
return date('t', strtotime($date));
}
$this->getLastDateOfMonth(01); //31
Ecco una funzione 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));
}
Ciò produrrebbe quanto segue:
echo get_number_of_days_in_month(2,2014);
Uscita: 28
Ci sono modi per ottenere l'ultimo giorno del mese.
//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]);
Sono in ritardo, ma ci sono alcuni semplici modi per farlo, come detto:
$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")));
Usare mktime () è il mio obiettivo per un controllo completo su tutti gli aspetti del tempo ... IE
echo "<br> ".date("Y-n-j",mktime (date("H"),date("i"),date("s"),(11+1),0,2009));
Impostando il giorno su 0 e spostando il mese in alto 1, si otterrà l'ultimo giorno del mese precedente. 0 e numeri negativi hanno l'effetto simile nelle diverse argomentazioni. PHP: mktime - Manuale
Come alcuni hanno detto, lo strtotime non è il modo più solido di procedere e poco se nessuno è altrettanto versatile.
Sto usando strtotime con cal_days_in_month come segue:
$date_at_last_of_month=date('Y-m-d', strtotime('2020-4-1
+'.(cal_days_in_month(CAL_GREGORIAN,4,2020)-1).' day'));
L'ho inserito nella mia classe di supporto data / ora qui
https://github.com/normandqq/Date-Time-Helper
utilizzando
$dateLastDay = Model_DTHpr::getLastDayOfTheMonth();
Ed è fatto
Un altro modo usando mktime e non 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 :)
Quindi in questo modo calcola se è 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); }
}
Questo è un modo molto più elegante per ottenere la fine del mese:
$thedate = Date('m/d/Y');
$lastDayOfMOnth = date('d', mktime(0,0,0, date('m', strtotime($thedate))+1, 0, date('Y', strtotime($thedate))));
È possibile utilizzare " t" nella funzione data per ottenere il numero del giorno in un determinato mese.
Il codice sarà qualcosa del genere:
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";
Il codice si spiega da sé. Quindi spero che sia d'aiuto.