14

How can I get the last day (Dec 31) of the current year as a date using PHP?

I tried the following but this doesn't work:

$year = date('Y');
$yearEnd =  strtotime($year . '-12-31');

What I need is a date that looks like 2014-12-31 for the current year.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
user2571510
  • 11,167
  • 39
  • 92
  • 138

4 Answers4

22

PHP strtotime() uses the current date/time as a basis (so it will use this current year), and you need date() to format:

$yearEnd = date('Y-m-d', strtotime('Dec 31'));

//or

$yearEnd = date('Y-m-d', strtotime('12/31'));
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
15

You can just concatenate actual year with required date

$year = date('Y') . '-12-31';
echo $year;
//output 2014-12-31
Fabio
  • 23,183
  • 12
  • 55
  • 64
15

DateTime is perfectly capable of doing this:

$endOfYear = new \DateTime('last day of December this year');

You can even combine it with more modifiers to get the end of next year:

$endOfNextYear = new \DateTime('last day of December this year +1 years');
xtra
  • 748
  • 9
  • 13
  • How can i pass an year as a parameter and get the last day of the year ? – Ângelo Rigo Oct 15 '18 at 13:56
  • In that case simply pass the year `$endOfYear = new \DateTime('last day of December 2019');` but bear in mind that this only works for years >1000 as for lower years you will get a 'Failed to parse time string' exception. – xtra Jan 23 '19 at 21:14
  • Note that the string "last day of December this year" can be useful to use with the `modify()` function. – COil Jan 24 '19 at 08:36
  • To get the last day of last year use `"last day of december last year"` – theking2 Aug 03 '22 at 09:39
4

Another way to do this is use the Relative Formats of strtotime()

$yearEnd = date('Y-m-d', strtotime('last day of december this year'));

// or

$yearEnd = date('Y-m-d', strtotime('last day of december'));
Maurice
  • 171
  • 1
  • 8