3 回答

TA貢獻1883條經驗 獲得超3個贊
如果您知道UTC偏移量,則可以使用以下函數傳遞它并獲取時間:
function calcTime(city, offset) {
// create Date object for current location
var d = new Date();
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time for city"+ city +" is "+ nd.toLocaleString();
}
alert(calcTime('Bombay', '+5.5'));

TA貢獻1815條經驗 獲得超10個贊
您可以使用Intl.DateTimeFormat。
var options = {
timeZone: 'Europe/London',
year: 'numeric', month: 'numeric', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric',
},
formatter = new Intl.DateTimeFormat([], options)
formatter.format(new Date())
另外,如果您只格式化一次而不是批量使用Date.prototype.toLocaleDateString()。
(new Date()).toLocaleString([], options)
不幸的是瀏覽器不要求了解比UTC其他時區,所以try這些塊,并計算出在情況下,它失敗的替代,例如取時區從服務器偏移。

TA貢獻1775條經驗 獲得超8個贊
最好的方法是使用getLocaleString,如下所示:
創建一個日期對象:
date = new Date(0)
如果您在柏林,則應將其轉換為以下字符串:
1970年1月1日星期四01:00:00 GMT + 0100(CET)
獲取雅典的時間:
date.toLocaleString('de-DE', {hour: '2-digit', hour12: false, timeZone: 'Europe/Athens' })
'02'
獲取上海時間:
date.toLocaleString('de-DE', {hour: '2-digit', hour12: false, timeZone: 'Asia/Shanghai' })
'08'
添加回答
舉報