We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 43621
    • 40 Posts
    Hi all,
    I have to synchronise the current servertime from my PHP script with my Javascript script (which only gets the client-time as far as I know).

    I had several thoughts of how to get it done but I'm not sure what is a "clean" way and not only a bad workaround.

    "My way" feels not like the way I should to it: run a php snippet which returns the timestamp and write it into an empty div (id="time") and read that with javascript.


    What do you think is the right way? Is there any way to get the server-time directly with js?

    Thnks in advance

    This question has been answered by BobRay. See the first response.

    • discuss.answer
      • 3749
      • 24,544 Posts
      There's not way to get it directly, since the JS if running on the client's machine, and as you say, you'll get that time instead of the server time.

      Your way is fine, but you can also do something like this, which would be a little faster:

      in the JS:

      var serverTime=[[+server_time]];


      in a snippet:

      $modx->setPlaceholder('server_time', time());


      or even faster if you're handling the JS code itself in the snippet:

      $code = str_replace('[[+server_time]]', time(), $code);


        Did I help you? Buy me a beer
        Get my Book: MODX:The Official Guide
        MODX info for everyone: http://bobsguides.com/modx.html
        My MODX Extras
        Bob's Guides is now hosted at A2 MODX Hosting
        • 43621
        • 40 Posts
        You're glorious!

        I wasn't aware that I can put placeholders into the JS but it's clear .. PHP processes the whole code and not only HTML markup. Thanks for the answer. Solved my problem.


        [e] I solved it now in a slightly another way:

        serverTime = [[!getServertime]] * 1000

        the snippet:
        return time();


        this is easier to use for me, especially cause I wanted to use strtotime() too cause this is much more easy to use than javascript time-functions smiley :

        nextWeekday = [[!getNextWeekday?nextDay=`Friday`]] * 1000

        the snippet:
        return strtotime("next $nextDay 00:00 CET") //returns the time of the upcoming defined day at 00:00 CET


        [ed. note: diluvian last edited this post 9 years, 6 months ago.]
          • 3749
          • 24,544 Posts
          That's a better, and slightly faster, solution. smiley
            Did I help you? Buy me a beer
            Get my Book: MODX:The Official Guide
            MODX info for everyone: http://bobsguides.com/modx.html
            My MODX Extras
            Bob's Guides is now hosted at A2 MODX Hosting