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
That is simple
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
You can use
date.getTimezoneOffset()
to get the time difference (in minutes) between UTC and thedate
object. It returns a negative value ifdate
is ahead of UTC, and a positive value if it is behind. That makes it possible to add those minutes to yourdate
object to convert it to UTC.