0

I could not find any document in relation to what I am trying to solve, hence I am asking it here.

My controller pulls a Carbon Date using this:

$utctime = Carbon::now()->toTimeString();

That code allows me to display the UTC time on my page. The problem comes in the fact that Carbon only loads the time once (on page load) and it stays at that time. What I want is to Carbon to display the real-time and not require the page to reload.

I am guessing it might not be possible the update the time, as Carbon is not front-end? If so, how would you go about making the time update every second instead of it not updating at all? - Maybe there is something for the front-end that I can use?

8
  • Like some kind of clock, right?
    – Hackerman
    Aug 29, 2017 at 16:36
  • Why not just pulling it once on page load and then let JavaScript to keep updating it?
    – Giedrius
    Aug 29, 2017 at 16:40
  • @Hackerman Yes, that is correct. Aug 29, 2017 at 16:42
  • @Giedrius I guess that would be the best way to do it! (Unless there is a 'Carbon' way to do it.) Aug 29, 2017 at 16:43
  • I was exactly to point that out...a clock routine with javascript....@spacetravel can you post the code where you render the $utctime in the View?
    – Hackerman
    Aug 29, 2017 at 16:44

2 Answers 2

2

Adding a basic ticking clock in Javascript is fairly straightforward:

<div id="time"></div>

<script type="text/javascript">
  function showTime() {
    var date = new Date(),
        utc = new Date(Date.UTC(
          date.getFullYear(),
          date.getMonth(),
          date.getDate(),
          date.getHours(),
          date.getMinutes(),
          date.getSeconds()
        ));

    document.getElementById('time').innerHTML = utc.toLocaleTimeString();
  }

  setInterval(showTime, 1000);
</script>

This would be entirely front-end based, and ensure there isn't a "jump" between the initially rendered server-time and the user's local time.

2
  • Would it be possible to output UTC time instead my local time? The clock works, but it displays my local time. Thanks! Aug 29, 2017 at 16:54
  • 1
    @spacetravel Edited. JS really isn't the nicest language for manipulating dates, so if you want to do anything more complicated than this, I'd recommend looking into a library like Moment.js
    – iainn
    Aug 29, 2017 at 17:00
0

You can use moment.js, you can also define the timezone or display UTC time

moment.utc().format();

https://momentjs.com/docs/ https://momentjs.com/timezone/docs/

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.