Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

javascript - Calculating a date and time in another time zone

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...