Possible Duplicate:
Convert date to another timezone in javascript




如何使该程序获得台北的时间?他们要修理的东西吗?还是我需要为此添加一些代码?

var yudan = "";
var now = new Date();
var month = now.getMonth() + 1;
var date = now.getDate();
var year = now.getFullYear();
if (year < 2000) year = year + 1900;

document.write(year + "." + yudan + month + "." + date + ".");




document.write("<span id=\"yudan_clock\"><\/span>");
var now,hours,minutes,seconds,timeValue;
function yudan_time(){
now = new Date();
hours = now.getHours();
minutes = now.getMinutes();
seconds = now.getSeconds();
timeValue = (hours >= 12) ? " " : " ";
timeValue += ((hours > 12) ? hours - 0 : hours) + ":";
timeValue += ((minutes < 10) ? " 0" : " ") + minutes + ":";
timeValue += ((seconds < 10) ? " 0" : " ") + seconds + "";
document.getElementById("yudan_clock").innerHTML = timeValue;
setTimeout(yudan_time, 100);}
yudan_time();

最佳答案

如果问题是使时钟显示台北时间,请使用getTimezoneOffset()方法。这使您可以定义UTC / GMT与所需时区(在台北,它是UTC + 8)之间的时间偏移。然后,您可以使用一组UTC计时方法,例如now.getUTCMonth()代替now.getMonth()

所以这就是您的代码的外观:

var yudan = "";
var now = new Date();
var month = now.getUTCMonth() + 1;
var date = now.getUTCDate();
var year = now.getUTCFullYear();
if (year < 2000) year = year + 1900;
document.write(year + "." + yudan + month + "." + date + ".");

document.write("<span id=\"yudan_clock\"><\/span>");
var now,hours,minutes,seconds,timeValue;
function yudan_time(){
now = new Date();
hours = now.getUTCHours() + (now.getTimezoneOffset()/60);
minutes = now.getUTCMinutes();
seconds = now.getUTCSeconds();
timeValue = (hours >= 12) ? " " : " ";
timeValue += ((hours > 12) ? hours - 0 : hours) + ":";
timeValue += ((minutes < 10) ? " 0" : " ") + minutes + ":";
timeValue += ((seconds < 10) ? " 0" : " ") + seconds + "";
document.getElementById("yudan_clock").innerHTML = timeValue;
setTimeout(yudan_time, 100);}
yudan_time();


请记住,getTimezoneOffset()方法以分钟为单位返回值;对于台北市,它将返回480,因此您需要除以60才能获得小时数。

希望这可以帮助!

09-04 13:40