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

Asked

Viewed 2,971 times

4

Is there any native function who identifies How many days is the month?

Example:

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

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

If not there is native function, how could you do?


Before you ask: has leap year (February with 29).

4 answers

7


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

This function will return the number of days in a year Month to the specified Calendar.

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

Where:

  • Calendar to use in the calculation

  • Month: Month to be selected in the calendar

  • year: Year in selected calendar

Example:

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

6

How did I respond in /a/109277/3635 I would say that the best way to do this is by using a native function created for this:

echo cal_days_in_month(CAL_GREGORIAN, 8, 2018);

4

 $funcao = new DateTime("2018-08");

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

date - string of the format parameter

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

example - ideone

-2

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

Returns number of days of the current month.

Manual Date PHP

  • The suggestion is good, but to catch the current month, to catch another month and year there would have to use strtotime what complicates, but you can adapt as a function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.