Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This has been driving me around the twist for several days now.

The application is in JavaScript.

I'm wish to show the time in one time zone for a viewer in another time zone.

I would store the time zone offset from GMT (Daylight saving would be taken in to account with the offset) for the zone I want to display the time and date for.

I was planning on converting the time to Epoch and then adding or subtracting the offset and then convert to DD MM YYYY HH MM SS for the date calculated.

I've got to the point that I can no longer see the wood for the trees. Any thoughts on how to achieve this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
162 views
Welcome To Ask or Share your Answers For Others

1 Answer

Since Dates are based on a UTC time value, you can just adjust for the offset you want and read UTC values, e.g.

/* @param {number} offset - minutes to subtract from UTC to get time in timezone
**
*/
function getTimeForOffset(offset) {
  function z(n){return (n<10?'0':'')+n}
  var now = new Date();
  now.setUTCMinutes(now.getUTCMinutes() - offset);
  return z(now.getUTCHours()) + ':' + z(now.getUTCMinutes()) + ':' + z(now.getUTCSeconds());
}

// Time for AEST (UTC+10)
console.log(getTimeForOffset(-600));

// Time for CEST (UTC+02)
console.log(getTimeForOffset(-120));

Note that the offset has the same sign as the javascript Date timezone offset, which is opposite to the typical value that is added to UTC to get the local time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...