I am formatting a Date on PHP using the following code:
$date = "2014-11-01";
$date_formatted = gmdate("Y-m-d", strtotime($date));
When I print them, the formatted date goes a day back. I was quite surprised. I am not simply looking for a solution (there are many for simple stuff like this). I would like to know how that happened.
echo $date . " ---> " . $date_formatted;
//Displays: 2014-11-01 ---> 2014-10-31
It's because you use gmdate
. This will give you a date in GMT based on the supplied timestamp.
strtotime will not use GMT by default and instead use your local timezone. So when you call gmdate
, it will reduce the date and time by your timezone offset.
To fix this, use date
instead of gmdate
or set your system's timezone to UTC.