0

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???

1

2 Answers 2

3

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.

2
  • Thanks Brett that explains the issue but it seems the dates stored in the database are in our local timezone (UTC+13) so how do I reformat the date to d-m-Y format??
    – Pragman
    Feb 16, 2017 at 1:20
  • I believe there is a toString method of the $date object that takes a format parameter (and possibly locale parameter).
    – Brett
    Feb 17, 2017 at 2:01
1

You can try below code to convert the date into your desired format:

$currentDate = Mage::getModel('core/date')->date('d-m-Y', strtotime($_item->getCreatedTime()));

Also FYI, Since Magento is meant to be for multi-website / multi-lingual / multi-locale purpose, it’s always a good practice to format the date using Magento’s date/time function. There is no need for conversion of date/time while inserting into the database. The formatting/conversion thing is only done at the frontend level for displaying purposes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.