0

I just took the JQuery function I found on stackoverflow to update time :

$(document).ready(function () {

  var serverTime = new Date();

  function updateTime() {
    /// Increment serverTime by 1 second and update the html for '#time'
    serverTime = new Date(serverTime.getTime() + 1000);
    $('#actual_time').html(serverTime);
  }

  $(function() {
    updateTime();
    setInterval(updateTime, 1000);
  });

})

But now I'm trying, unsuccessfully to change format with a code like this.

serverTime2 = new $.format.date(new Date(serverTime.getTime() + 1000), 'g:i A')

I would like to change de date format to 'g:i A' and I'd also like, instead of serverTime, to apply a specific GMT to my date.

Can you help me please ?

Kiji_T
  • 104
  • 10
  • What library are you using for `$.format.date`? That's not a part of jquery. Or is that in your php? Please make it clear what you're trying to change and where and exactly what the issue is. – freedomn-m Apr 30 '21 at 08:45

1 Answers1

1

No need for JQuery here. Try using toLocaleTimeString.

const locale24HourTime = (tz, date) => date.toLocaleTimeString("en-EN", {
    timeZone: tz, hourCycle: 'h23', hour: "2-digit",
    minute: "2-digit", second: "2-digit" });

const date1 = new Date();
console.log(`Atlantic/Reykjavik: ${locale24HourTime(`Atlantic/Reykjavik`, date1)}`);
console.log(`Asia/Kolkata: ${locale24HourTime(`Asia/Kolkata`, date1)}`);
console.log(`Asia/Shanghai: ${locale24HourTime(`Asia/Shanghai`, date1)}`);
console.log(`Europe/London: ${locale24HourTime(`Europe/London`, date1)}`);
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • Indeed it works but, in my PHP code, I'm reformating hour by doing ltrim(date('g:i A', (time() + 3600 * (int)$diff_time))) and $diff_time is the +1 or +2 from GMT I'm getting from an API. So I cannot use my API data with JQuery right ? Or maybe putting it in a hidden div could be the solution. – Kiji_T Apr 30 '21 at 08:29
  • 1
    There was no mention of PHP in your question. If you want to manipulate a date *client side*, its value depends on the actual date it receives from the server. I'd suggest you focus on delivering a UTC date from the server and use the `locale24HourTime`-function of the answer within the client for that. [Here](https://stackblitz.com/edit/js-state-machine) you'll find a small experiment using UTC date values delivered from [a sunset-rise](https://sunrise-sunset.org/api)-API (hover the question mark for time manipulation results). – KooiInc Apr 30 '21 at 09:06