Get last day of month php

Asked 12 years, 10 months ago

Viewed 602k times

How can I get the last day of the month in PHP?

Given:

$a_date = "2009-11-23"

I want 2009-11-30; and given

$a_date = "2009-12-23"

I want 2009-12-31.

Foreever

6,5548 gold badges48 silver badges55 bronze badges

asked Nov 6, 2009 at 10:27

Mithun SreedharanMithun Sreedharan

48.5k69 gold badges179 silver badges234 bronze badges

0

t returns the number of days in the month of a given date [see the docs for date]:

$a_date = "2009-11-23";
echo date["Y-m-t", strtotime[$a_date]];

SilentGhost

292k64 gold badges300 silver badges291 bronze badges

answered Nov 6, 2009 at 10:32

Dominic RodgerDominic Rodger

95.1k33 gold badges196 silver badges211 bronze badges

10

The code using strtotime[] will fail after year 2038. [as given in the first answer in this thread] For example try using the following:

$a_date = "2040-11-23";
echo date["Y-m-t", strtotime[$a_date]];

It will give answer as: 1970-01-31

So instead of strtotime, DateTime function should be used. Following code will work without Year 2038 problem:

$d = new DateTime[ '2040-11-23' ]; 
echo $d->format[ 'Y-m-t' ];

answered Mar 1, 2012 at 1:51

6

I know this is a little bit late but i think there is a more elegant way of doing this with PHP 5.3+ by using the DateTime class :

$date = new DateTime['now'];
$date->modify['last day of this month'];
echo $date->format['Y-m-d'];

answered Aug 20, 2013 at 7:50

Hannoun YassirHannoun Yassir

19.9k23 gold badges76 silver badges111 bronze badges

10

This should work:

$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].'
'; echo date['D, M jS Y', $week_end].'
'; echo date['D, M jS Y', $month_start].'
'; echo date['D, M jS Y', $month_end].'
'; echo date['D, M jS Y', $year_start].'
'; echo date['D, M jS Y', $year_end].'
';

answered Nov 19, 2012 at 22:35

kaleazykaleazy

5,5482 gold badges45 silver badges50 bronze badges

The most elegant for me is using DateTime

I wonder I do not see DateTime::createFromFormat, one-liner

$lastDay = \DateTime::createFromFormat["Y-m-d", "2009-11-23"]->format["Y-m-t"];

answered Sep 7, 2016 at 23:23

john Smithjohn Smith

16.8k11 gold badges71 silver badges113 bronze badges

1

Try this , if you are using 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'];

For finding next month last date, modify as follows,

 $date->modify['last day of 1 month'];
 echo $date->format['Y-m-d'];

and so on..

answered Nov 12, 2014 at 6:02

Mohammed SafeerMohammed Safeer

19.6k8 gold badges73 silver badges78 bronze badges

1

You could create a date for the first of the next month, and then use strtotime["-1 day", $firstOfNextMonth]

answered Nov 6, 2009 at 10:36

nikc.orgnikc.org

15.9k6 gold badges47 silver badges83 bronze badges

4

You can find last day of the month several ways. But simply you can do this using PHP strtotime[] and date[] function.I'd imagine your final code would look something like this:

$a_date = "2009-11-23";
echo date['Y-m-t',strtotime[$a_date]];

Live Demo

But If you are using PHP >= 5.2 I strongly suggest you use the new DateTime object. For example like below:

$a_date = "2009-11-23";
$date = new DateTime[$a_date];
$date->modify['last day of this month'];
echo $date->format['Y-m-d'];

Live Demo

Also, you can solve this using your own function like below:

/**
 * 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];

answered Feb 11, 2017 at 3:45

FaisalFaisal

4,3742 gold badges39 silver badges49 bronze badges

1

Your solution is here..

$lastday = date['t',strtotime['today']];

bensiu

23.2k52 gold badges72 silver badges113 bronze badges

answered Nov 6, 2012 at 4:29

1

Nowadays DateTime does this quite conveniently if you have month and year you can

$date = new DateTime['last day of '.$year.'-'.$month];

From another DateTime object that would be

$date = new DateTime['last day of '.$otherdate->format['Y-m']];

answered Jun 18, 2020 at 16:28

MaxMax

2,39921 silver badges26 bronze badges

If you use the Carbon API extension for PHP DateTime, you can get the last day of the month with:

$date = Carbon::now[];
$date->addMonth[];
$date->day = 0;
echo $date->toDateString[]; // use toDateTimeString[] to get date and time 

answered Jul 28, 2014 at 12:09

eaykineaykin

3,6031 gold badge35 silver badges32 bronze badges

3

You can also use it with datetime

$date = new \DateTime[];
$nbrDay = $date->format['t'];
$lastDay = $date->format['Y-m-t'];

answered Jul 1, 2013 at 13:48

AjouveAjouve

9,28724 gold badges83 silver badges130 bronze badges

Carbon API extension for PHP DateTime

Carbon::parse["2009-11-23"]->lastOfMonth[]->day;

or

Carbon::createFromDate[2009, 11, 23]->lastOfMonth[]->day;

will return

30

answered Sep 17, 2016 at 7:59

josefjosef

8049 silver badges7 bronze badges

1

$date1 = $year.'-'.$month; 
$d = date_create_from_format['Y-m',$date1]; 
$last_day = date_format[$d, 't'];

answered Jul 16, 2013 at 1:04

kaylakayla

1561 silver badge12 bronze badges

If you have a month wise get the last date of the month then,

public function getLastDateOfMonth[$month]
    {
        $date = date['Y'].'-'.$month.'-01';  //make date of month 
        return date['t', strtotime[$date]]; 
    }

$this->getLastDateOfMonth[01]; //31

answered Feb 25, 2019 at 6:26

2 lines code and you are done:

$oDate = new DateTime["2019-11-23"];

// now your date object has been updated with last day of month    
$oDate->setDate[$oDate->format["Y"],$oDate->format["m"],$oDate->format["t"]];

// or to just echo you can skip the above line using this
echo $oDate->format["Y-m-t"];

answered Feb 16, 2021 at 18:06

justnajmjustnajm

4,1256 gold badges34 silver badges55 bronze badges

Using Zend_Date it's pretty easy:

$date->setDay[$date->get[Zend_Date::MONTH_DAYS]];

answered Feb 3, 2016 at 14:55

An other way using mktime and not 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 :]

So this way it calculates either if it is 31,30 or 29

answered Sep 8, 2016 at 9:02

I am using strtotime with cal_days_in_month as following:

$date_at_last_of_month=date['Y-m-d', strtotime['2020-4-1
+'.[cal_days_in_month[CAL_GREGORIAN,4,2020]-1].' day']];

answered Apr 9, 2020 at 12:34

RaniRani

3024 silver badges7 bronze badges

Here is a complete function:

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]];
}

This would output following:

echo get_number_of_days_in_month[2,2014];

Output: 28

answered Feb 20, 2014 at 8:17

FirzeFirze

3,6815 gold badges45 silver badges61 bronze badges

There are ways to get last day of month.

//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]]; 

answered Jul 24, 2014 at 5:36

vineetvineet

13.2k10 gold badges53 silver badges75 bronze badges

I am late but there are a handful of easy ways to do this as mentioned:

$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"]]];

Using mktime[] is my go to for complete control over all aspects of time... I.E.

echo "
".date["Y-n-j",mktime [date["H"],date["i"],date["s"],[11+1],0,2009]];

Setting the day to 0 and moving your month up 1 will give you the last day of the previous month. 0 and negative numbers have the similar affect in the different arguements. PHP: mktime - Manual

As a few have said strtotime isn't the most solid way to go and little if none are as easily versatile.

answered Feb 9, 2017 at 17:26

JSGJSG

3604 silver badges12 bronze badges

if you want to go back few months you can do something like this as well.

 $list = [
        0, 1, 2, 3
    ];

    $date = new \Datetime[];
    $dates = [];
    foreach[$list as $item]
    {

        $set = clone $date;
        $set->modify["-$item month "];
       $dates[] = $set->modify["last day of this month"];
       
    }
    return $dates;

answered Jan 21, 2021 at 16:16

    $startDate = '2011-12-01';
    $endDate = date['Y-m'];
    while [true] {
        try {
            $startDateTime = new DateTime[$startDate];
            $startDateTime->add[new DateInterval['P1M']];
            $startDate = $startDateTime->format['Y-m-d'];
            $endTime = $startDateTime->format['Y-m-t'];
            echo $startDate . ' => ' . $endTime . PHP_EOL;
            if [$startDateTime->format['Y-m'] == $endDate] {
                break;
            }
        } catch [Exception $exception] {
            var_dump[$exception->getMessage[]];
            break;
        }
    }

After testing many solutions, this works best for me.

answered Jul 7, 2020 at 9:48

Winn Minn SoeWinn Minn Soe

3411 gold badge2 silver badges4 bronze badges

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]; }
}

//zkinformer.com/?p=134

kaiser

21.1k16 gold badges87 silver badges106 bronze badges

answered Mar 20, 2012 at 4:23

KevinKevin

71 bronze badge

0

I needed the last day of the next month, maybe someone will need it:

echo date["Y-m-t", strtotime["next month"]]; //is 2020-08-13, return 2020-09-30

answered Aug 13, 2020 at 12:12

This a much more elegant way to get the end of the month:

  $thedate = Date['m/d/Y']; 
  $lastDayOfMOnth = date['d', mktime[0,0,0, date['m', strtotime[$thedate]]+1, 0, date['Y', strtotime[$thedate]]]]; 

answered Jul 30, 2015 at 16:59

You can use "t" in date function to get the number of day in a particular month.

The code will be something like this:

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 

Chủ Đề