1

I have a clock like so:

const timeContainer = document.querySelector('.timeContainer');

var showTime = (timeZone) => {
  let utcTime = new Date().toUTCString();
  //need to subtract/add timezone from utcTime
  //need to remove everything except for time e.g. 00:22:22
  return utcTime;
};

setInterval( () => {
  timeContainer.innerHTML = showTime('-8');
}, 1000);

Which gives me GMT time like this:

Tue, 29 Nov 2016 00:35:54 GMT

.. which is what I want! But say I want to get the time in Hong Kong, and also only the numerical time, none of the date and timezone information.

I basically need to:

a) subtract/add a variable timeZone integer from utcTime

b) remove all text in output except for the time, e.g. utcTime only outputs as 00:22:22

I basically need to generate a clock based on what timeZone integer I run showTime with, for example:

showTime(-5);
//returns time in EST timezone
showTime(-6);
//returns time in CST timezone

etc. Is there a way to do this using .toUTCString()? Or is there a better method?

Here's a jsFiddle with my code.

3
  • I suggest that you consider using moment-timezone. Commented Nov 29, 2016 at 1:06
  • What is your question or issue then? Commented Nov 29, 2016 at 1:07
  • edited my question for clarity Commented Nov 29, 2016 at 1:12

2 Answers 2

1

Get the timestamp which is time since the epoch in UTC, offset by the desired timezone and build the string.

const timeContainer = document.querySelector('.timeContainer');

var dateToTimeString = (dt) => {
  let hh = ('0' + dt.getUTCHours()).slice(-2);
  let mm = ('0' + dt.getUTCMinutes()).slice(-2);
  let ss = ('0' + dt.getUTCSeconds()).slice(-2);
  return hh + ':' + mm + ':' + ss;
}

var showTime = (timeZone) => {
  // convert timezone in hours to milliseconds
  let tzTime = new Date(Date.now() + timeZone * 3600000);
  return dateToTimeString(tzTime);
};

setInterval( () => {
  timeContainer.innerHTML = showTime('-8');
}, 1000);

jsFiddle

Which will output

17:00:00
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, sorry if it wasn't clear enough. I want to be able to put in any sort of timezone modifier and easily generate the time at that location. for instance if I ran showTime(-5) I would get EST, showTime(-6) CST, etc.
0

If you want the time in the "11/29/2016" format you can use toLocaleDateString() instead of toUTCString().

If you want the time in the "Tue Nov 29 2016" format you can use toDateString() instead of toUTCString().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.