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];
}
添加回答
举报