I've just noticed that PHP date function acts weird, can someone explain me what i'm doing wrong?
Following code displays same results
<?php
echo date('Y-m-t');
// Outputs last day of this month: 2016-03-31
echo date('Y-m-t', strtotime("-1 month"));
// For some reason outputs the same: 2016-03-31
echo date('Y-m-t', strtotime("+1 month"));
// Outputs 2016-05-31
It might be just me being stupid, but could someone explain me why this happens?
When using t
in your date('Y-m-t')
call you're referring to:
t
- Number of days in the given month
If you tried Y-m-d
you'd figure out that it's 2 different dates:
<?php
var_dump( date('Y-m-d') );
var_dump( date('Y-m-d', strtotime('-1 month') ) );
string(10) "2016-03-31
"
string(10) "2016-03-02
"
To fix this issue you can use the strtotime
format last day of last month
:
<?php
var_dump( date('Y-m-d') );
var_dump( date('Y-m-d', strtotime('last day of last month') ) );
which results in:
string(10) "2016-03-31
"
string(10) "2016-02-29
"
Try date('Y-m-d', strtotime("-1 month"))
, what does that display? March 2nd. Why? Because February 31st doesn't exist, and PHP does date rollover math.
The basic issue is that "minus one month" is very vaguely and ill defined. What should happen when that lands on dates like "February 31st"? There's no good or correct answer. Don't leave it up to PHP to decide the outcome. Explicitly deduct one month from the first of a month if you expect a defined outcome.