1 回答

TA貢獻1798條經驗 獲得超7個贊
您可以使用Luxon來做到這一點:
const dt = luxon.DateTime.fromObject({hour: 10, zone: 'America/Los_Angeles'});
console.log('Time in time zone: ' + dt.toString());
console.log('Unix (epoch) timestamp in milliseconds: ' + dt.toMillis());
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.25.0/luxon.min.js"></script>
這是有效的,因為當您不提供日期組件時,Luxon 使用提供的時區中的當前日期作為基礎。此外,當您提供任何時間分量時,剩余時間分量將設置為零。因此,您需要設置的只是小時和時區。

TA貢獻1829條經驗 獲得超6個贊
嘗試這樣的事情:
function calcTime(city, offset) {
d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000*offset));
return "The local time in " + city + " is " + nd.toLocaleString();
}
// get Bombay time
console.log(calcTime('Bombay', '+5.5'));
// get Singapore time
console.log(calcTime('Singapore', '+8'));
// get London time
console.log(calcTime('London', '+1'));
另一種方法是使用選項對象,因為它有一個 timeZoneName 參數
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// an application may want to use UTC and make that visible
var options = { timeZone: 'UTC', timeZoneName: 'short' };
console.log(date.toLocaleTimeString('en-US', options));
// → "3:00:00 AM GMT"
// sometimes even the US needs 24-hour time
console.log(date.toLocaleTimeString('en-US', { hour12: false }));
// → "19:00:00"
// show only hours and minutes, use options with the default locale - use an empty array
console.log(date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }));
// → "20:01"
如果您希望它返回日期對象而不是字符串,以下解決方案將適合您:
var d = new Date();
var date_object = new Date(formatDate(d.toLocaleString('en-US', { 'timeZone': 'America/New_York', 'hour12': false })));
function formatDate(date){
var date = date.split(', ')[0].split('/');
var time = date.split(', ')[1].split(':');
return date[2]+'-'+date[0]+'-'+date[1]+'T'+time[0]+':'+time[1]+':'+time[2];
}
添加回答
舉報