为了账号安全,请及时绑定邮箱和手机立即绑定

如何获取特定时区一天中特定时间的纪元时间?

如何获取特定时区一天中特定时间的纪元时间?

森栏 2023-08-18 16:11:53
我正在尝试获取特定时区当天的纪元时间戳。例如,我想知道太平洋标准时间今天早上 6 点的纪元时间戳我非常接近,但不确定如何调整时区:const getTimestampFor10amPST = () => {  const today = new Date()  const year = today.getFullYear()  const month = today.getMonth()  const day = today.getDate()  const timestampFor10amPST = new Date(year, month, day, 10, 0, 0, 0);  return timestampFor10amPST.getTime()}如何获取预期时区的时间戳?
查看完整描述

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 使用提供的时区中的当前日期作为基础。此外,当您提供任何时间分量时,剩余时间分量将设置为零。因此,您需要设置的只是小时和时区。



查看完整回答
反对 回复 2023-08-18
?
肥皂起泡泡

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];

}


查看完整回答
反对 回复 2023-08-18
  • 1 回答
  • 0 关注
  • 92 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信