0

I created a really simple block in my child theme:

/Magento_Theme/layout/default.xml:

<referenceContainer name="content">
    <block class="Magento\Framework\View\Element\Template" name="custom_time_block" template="Magento_Theme::html/custom-time-block.phtml" before="-"/>
</referenceContainer>

/Magento_Theme/templates/html/custom-time-block.phtml:

<div class="container">
        <div class="row">
             <div class="col-sm-12 text-center">
                 <?php
                 $now = new DateTime();
                 echo $now->format('H:i:s');
                 ?>
             </div>
        </div>
 </div>

So when I clear the cache, the time that is displayed, is the time when I cleared the cache. The time is not the current time. So how can I get this working without:

  • cacheable="false" (because this block is going to be dislayed everywhere, so each page will not be cached)
  • Javascript: I want to display the server time, not the client time

Thank you in advance!

3
  • why not AJAX it will give you updated time without cache
    – kunj
    Commented May 27, 2018 at 9:16
  • Thank you for your comment @kunj. That might be a solution. Is there an existing API endpoint I can use to GET the current time?
    – MrPaulsky
    Commented May 27, 2018 at 9:21
  • API? you can try this magento.stackexchange.com/questions/196432/…
    – kunj
    Commented May 27, 2018 at 9:28

1 Answer 1

1

I ended up using Javascript with MomentJs. I echo the date into a hidden input like this

<input type="hidden" id="system-time" value="<?php echo $now->format(DATE_ISO8601); ?>" />

Yes, this is still cached, but it doesn't matter because I can parse the string with MomentJS to get the correct TimeZone like this:

 var systemTime = moment().utcOffset($('#system-time').val());

or

 var systemTime = moment().parseZone($('#system-time').val());

I found information about this here: http://www.herveguetin.com/formatting-date-times-and-displaying-them-nicely-with-moment-js/. That article explains how to display date and time in Magento 2 with MomentJS.

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.