0

I'm trying to change the date format from 3/6/22 to 03/06/2022 in this file:

/app/code/Magento/Sales/view/frontend/templates/order/history.phtml

https://i.stack.imgur.com/7cnCT.jpg

How can I edit the following code?

<?= /* @noEscape */ $block->formatDate($_order->getCreatedAt()) ?>

1 Answer 1

1

As quick solution you can create helper in your module

<?php
declare(strict_types=1);

namespace Acme\StackExchange\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Locale\ResolverInterface;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;

class Date extends AbstractHelper
{
    /**
     * @var TimezoneInterface
     */
    protected $timezone;

    /**
     * @var string
     */
    protected $locale;

    public function __construct(Context $context, TimezoneInterface $timezone, ResolverInterface $localeResolver)
    {
        parent::__construct($context);
        $this->timezone = $timezone;
        $this->locale = $localeResolver->getLocale();
    }

    public function formatDate(string $value, string $format): string
    {
        $convertedDate = $this->timezone->date(
            new \DateTime($value, new \DateTimeZone('UTC')),
            $this->locale,
            true
        );

        return $convertedDate->format($format);
    }
}

and use this helper in template

// define it in the top
$_dateHelper = $this->helper(\Acme\StackExchange\Helper\Date::class);

// use
echo $_dateHelper->formatDate($_order->getCreatedAt(), 'm/d/Y');
6
  • Thanks for your help! i have following error with your code: ParseError: syntax error, unexpected 'echo' (T_ECHO). Why? Thanks Jun 3, 2022 at 22:21
  • Inside HTML use <?= $_dateHelper->formatDate($_order->getCreatedAt(), 'm/d/Y'); ?>. <?= equal <?php echo Jun 4, 2022 at 11:27
  • Okay thanks now error is different.. Error: Class 'MakeDo\DateTime\Helper\Date' not found in /home/web/aarte.com.au/www/lib/internal/Magento/Framework/ObjectManager/Factory/AbstractFactory.php:121 Jun 4, 2022 at 14:59
  • Make sure you properly registered your module MakeDo\DateTime and make sure you've specified correct namespace and class name for helper Jun 4, 2022 at 19:01
  • I made a quick video if you have time for check it :) we.tl/t-0N0udUag2q Jun 4, 2022 at 22:17

Your Answer

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

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