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?
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 of 2020-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.