I see that a stored date value in phpmyadmin is 2020-03-03. In PHP, I set the default timezone to UTC and the user’s timezone to America/New_York:
date_default_timezone_set('UTC');
$userTimeZone = new DateTimeZone('America/New_York');
I retrieve my date from the database, set the timezone on the date, and make it into a string. It now equals a day earlier. (03-02-2020)
$dateNeeded = new DateTime($row['dateNeeded']);
$dateNeeded->setTimeZone($userTimeZone);
$dateNeededStr = $dateNeeded->format('m-d-Y');
What did I do incorrectly here?
2
Answers
It is not incorrect. Your date is stored without the time component, which means when you put it in a
DateTime
constructor, it will be created as midnight ($dateNeeded = new DateTime($row['dateNeeded'])
will have the value of2020-03-03 00:00:00
.That’s in UTC timezone because you defined it so at the start. So when you change the timezone, it will move back (as New York is UTC – 5) and gain the value of
2020-03-02 19:00:00
.Since you’re only outputting the date in your format (and not the time), it comes out as a day early.
Dont use
date_default_timezone_set('UTC');
because MySQL server will use server timezone not UTC,In example,
Your server time zone is GMT +2
And you set your server timezone to GMT +0;
Then you read your date on database which stored on GMT + 2 time zone
When you try to convert it to other timezone, e.g. GMT + 5,
It will shift 7 hour not 5 hour