15

I want to output of last and first date of a given month of current year. I am using this code but not works

$month='02';
$first_day_this_month = date('Y-'.$month.'-01'); // hard-coded '01' for first day
$last_day_this_month  = date('Y-'.$month.'-t');

echo $first_day_this_month;print'<->';echo $last_day_this_month;

my output shows

2015-02-01<->2015-02-31

But it will be 2015-02-01<->2015-02-28

Frai1989
  • 163
  • 1
  • 1
  • 4

4 Answers4

23

I have had this problem with PHP before, try the following way:

$dateToTest = "2015-02-01";
$lastday = date('t',strtotime($dateToTest));
Ushal Naidoo
  • 2,704
  • 1
  • 24
  • 37
  • 1
    gg... strtotime will break after 2038? – 4 Leave Cover Dec 31 '16 at 08:23
  • 4
    21 years time.. I doubt the Unix timestamp as we know it will exist then. But if this "Y2K" issue still scares you then for MySQL, store dates as DATETIME rather than TIMESTAMP. http://stackoverflow.com/a/2012620/1618363 – Ushal Naidoo Jan 04 '17 at 01:55
  • This doesn't answer the question. See other question at https://stackoverflow.com/questions/1686724/how-to-find-the-last-day-of-the-month-from-date – Bilbo Dec 16 '21 at 23:03
11

You can use DateTime methods:

$month = '02';

$date = new DateTime(date('Y').'-'.$month.'-01');
$date->modify('last day of this month');
$last_day_this_month = $date->format('Y-m-d');
Solrac
  • 924
  • 8
  • 23
Gautier
  • 1,066
  • 1
  • 13
  • 24
6

there are many ways to do that, i give you two answers\ideas:

1- Try to use strtotime PHP function (http://php.net/manual/es/function.strtotime.php)

Something like date("Y-m-d", strtotime("last day of this month")); or first day... or any month.

2- Other way you can use that:

First day:

date("Y-m-d", mktime(0, 0, 0, *YOUR MONTH PARAM*,1 ,date("Y")));

Last day:

date("Y-m-d", mktime(0, 0, 0, *YOUR MONTH PARAM*+1,0,date("Y")));

Read about mktime function here:

http://php.net/manual/es/function.mktime.php

Good luck!

4

You can with DateTime class.

    $month='02';
    $first_day_this_month = date('Y-'.$month.'-01');

    $firstDayThisMonth = new \DateTime($first_day_this_month);

    $lastDayThisMonth = new \DateTime($firstDayThisMonth->format('Y-m-t'));
    $lastDayThisMonth->setTime(23, 59, 59);

    echo $firstDayThisMonth->format("Y-m-d");
    echo "<->";
    echo $lastDayThisMonth->format("Y-m-d");
ercvs
  • 337
  • 1
  • 5
  • 13