Identify how many days the month has (28, 29, 30, 31) [duplicate]

3

Is there a native function that identifies how many days does the month ?

Example:

value : 2018-08 , then return would be: 31 .

$dias = funcao('2018-08');
echo $dias; // resultado: 31

If there is no native function, how could you do it?

Before you ask: have the leap year (February 29th).

    
asked by anonymous 15.08.2018 / 13:31

4 answers

5

There is a native function of php for this, it is cal_days_in_month .

This function will return the number of days in a month of the year for the specified calendar.

int cal_days_in_month ( int $calendar , int $month , int $year )

Where:

  • calendar: Calendar to use in calculation

  • month: Month to be selected in the calendar

  • year: Year not selected calendar

Example:

<?php
    $dias = cal_days_in_month(CAL_GREGORIAN, 8, 2018); // 31
    echo "Existem ".$dias." dias em Agosto de 2018";
?>
    
15.08.2018 / 13:45
5

As I replied in link I would say the best way to do this is by using a native function created for this is it:

echo cal_days_in_month(CAL_GREGORIAN, 8, 2018);
    
15.08.2018 / 13:47
3
 $funcao = new DateTime("2018-08");

 $numDias = $funcao->format('t');

date - format parameter string

 format  |   Descrição                      |  Retorno
 ------------------------------------------------------
 t       |   Número de dias de um dado mês  | 28 até 31

example - ideone

    
15.08.2018 / 16:16
-1

You can use $days = date("t");

Returns number of days of the current month.

Manual Date PHP

    
15.08.2018 / 13:41