PHP – Fix Wrong Date Display Issue

datedatetimePHPtimezone

I am trying to display a date in the frontend.

Currently the code calls the date like so

<?php echo $date->date('m-d-Y', $_item->getCreatedTime()); ?>

the date in the database is: 2017-02-15 14:37:32

However in the frontend it gets displayed as: 02-16-2017 the format is correct but the date is wrong.
If I call the date like so:

<?php echo $_item->getCreatedTime(); ?>

It renders as 2017-02-15 14:37:32
So my question is can someone explain this to me and how can I get the date to display as d-m-Y format???

Best Answer

Times are store in the database as UTC (+0:00). When you use the $date object to render a date, it gets translated into your store's configured timezone.

For example, if the date is 2017-02-15 14:37:32 UTC, and your timezone is say "Lima" (UTC+11), then the calculated local time would be 2017-02-15 25:37:32. Since there is no 25th hour, the day is then incremented to be the 16th giving the date output you're seeing.

I'm not sure of what your timezone settings are, but I would guess that may be it. Magento sets the timezone during processing to be UTC for this specific reason. If you override that while storing dates/times, it can really give some weird results.