skip to Main Content

I have a script that I use to display the data/time on a website. This works ok but just works off the users/browser time.

On something new I’m working on, I’d like it to display the time in a specific timezone (GMT) always – is that possible?

I don’t need the month in this version, so you can see that commented out.

As an aside, even on the original version. The time ‘jumps’ into view as it takes a while to load – is there away to fix this?

Might be worth noting this is a simple static website, so no database or much else to play with to get the time.

Cheers!

function showDateTime() {
    var currentDate = document.getElementById("date");
    var currentTime = document.getElementById("time");
    
    var date = new Date();
    var dayList = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    /* var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; */
    var dayName = dayList[date.getDay()];
    /* var monthName = monthNames[date.getMonth()]; */
    /* var today = `${dayName} ${date.getDate()} ${monthName}`; */
    var today = `${dayName}`;
    
    var hour = ('0' + date.getHours()).substr(-2);
    var min = ('0' + date.getMinutes()).substr(-2);
    var sec = ('0' + date.getSeconds()).substr(-2);
    
    
    var time = hour + ":" + min + ":" + sec;
    currentDate.innerText = `${today}`;
    currentTime.innerText = `${time}`;
}
setInterval(showDateTime, 1000);
<p><span id="date" class="os-menu__item"></span> <span id="time"></span> GMT</p>            

2

Answers


  1. That is simple

    const todaySpan = document.getElementById("date");
    const re = /([a-zA-Z]+), (d+) ([a-zA-Z]+) (d+) ([d:]+) (w+)/;
    const showDateTime = () => {
      const [_, dayString, date, month, year, time, tz] = new Date().toUTCString().match(re); // toUTCString is GMT
      todaySpan.textContent =  `${dayString} ${time} ${tz}`
    };  
    showDateTime();
    setInterval(showDateTime, 1000);
    <p><span id="date" class="os-menu__item"></span></p>

    To have other dates than GMT have a look at this answer

    How to initialize a JavaScript Date to a particular time zone

    As RobG correctly mentions, you can use the INTL date functions too

    const todaySpan = document.getElementById("date");
    const opts = {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      weekday: 'short',
      timeZone: 'GMT',
      hour12: false,
      timeZoneName: 'shortGeneric'
    };
    
    const showDateTime = () => todaySpan.textContent = new Date().toLocaleString('en', opts);
    showDateTime();
    setInterval(showDateTime, 1000);
    <p><span id="date" class="os-menu__item"></span></p>
    Login or Signup to reply.
  2. You can use date.getTimezoneOffset() to get the time difference (in minutes) between UTC and the date object. It returns a negative value if date is ahead of UTC, and a positive value if it is behind. That makes it possible to add those minutes to your date object to convert it to UTC.

    const date = new Date();
    console.log("Original -> " + date.toLocaleTimeString());
    
    date.setMinutes(date.getMinutes() + date.getTimezoneOffset())
    console.log("Adjusted -> " + date.toLocaleTimeString());
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search