How to get the number of days of the current month?
Asked Answered
L

12

36

I want to check if today is the last day of the month, but I don't really know how.

Can you help?

Limann answered 11/9, 2010 at 13:25 Comment(1)
I came here to understand how to get the number of days of the current month (< if you are interested in it, read about the cal_days_in_month function). The title should be something like "PHP: How to check if today is the last day of the current month?"Musicology
M
59

There is probably a more elegant solution than this but you can just use php's date function:

$maxDays=date('t');
$currentDayOfMonth=date('j');

if($maxDays == $currentDayOfMonth){
  //Last day of month
}else{
  //Not last day of the month
}
Managua answered 11/9, 2010 at 13:31 Comment(1)
The time() calls are redundant since the current timestamp is what's used by default. Not that it matters though :)Villager
H
42

Try to use this:

date('t');
Hylophagous answered 11/9, 2010 at 13:31 Comment(0)
K
17

date('t');

or you may use

cal_days_in_month.

see here: http://php.net/manual/en/function.cal-days-in-month.php

Kenward answered 29/8, 2013 at 6:39 Comment(1)
cal_days_in_month is better method, you can give any specific month and year for itAphoristic
S
16

In order to get no. of days in month you can use either

date('t')

OR

cal_days_in_month(CAL_GREGORIAN, 8, 2003)

And if you wish to check if today is the last day of month us can use

if(date('d')==date('d',strtotime('last day of month'))){
//your code
}

strtotime offers many great features so check them out first

Saltatory answered 8/7, 2015 at 7:27 Comment(0)
B
6

Use php's function: cal_days_in_month

More details here

cal_days_in_month(CAL_GREGORIAN, 8, 2003);
Bessie answered 29/3, 2013 at 12:27 Comment(0)
R
5

Use date function:

if (date('t') == date('j'))
{
   ...
}
Refrigerant answered 11/9, 2010 at 13:29 Comment(0)
D
4
$date = new DateTime('last day of this month');
$numDaysOfCurrentMonth = $date->format('d');
Dacosta answered 25/9, 2017 at 13:48 Comment(0)
B
4

this is to find the days in any month:

$days = intval(date('t', strtotime($desiredDate)));
Benisch answered 24/3, 2020 at 11:17 Comment(0)
H
3
     echo date('t'); /// it return last date of current month
Hearse answered 18/4, 2019 at 12:29 Comment(0)
L
0

And here it is, wrapped up as a function:

function is_last_day_of_month($timestamp = NULL) {
    if(is_null($timestamp))
        $timestamp = time();
    return date('t', $timestamp) == date('j', $timestamp);
}
Lentil answered 11/9, 2010 at 13:44 Comment(0)
T
0

Using the modern DateTime object class:

$date = new DateTime('last day of this month');
Taker answered 11/2, 2017 at 9:57 Comment(0)
V
0

With DateTime ;)

    $date = new \DateTime('now');
    var_dump($date->format('t'));
Veneration answered 23/1 at 23:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.