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

我正在尝试获取特定时区当天的纪元时间戳。


例如,我想知道太平洋标准时间今天早上 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()

}

如何获取预期时区的时间戳?


森栏
浏览 96回答 1
1回答

元芳怎么了

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

肥皂起泡泡

尝试这样的事情:function calcTime(city, offset) {&nbsp; &nbsp; d = new Date();&nbsp; &nbsp; utc = d.getTime() + (d.getTimezoneOffset() * 60000);&nbsp; &nbsp; nd = new Date(utc + (3600000*offset));&nbsp; &nbsp; return "The local time in " + city + " is " + nd.toLocaleString();}// get Bombay timeconsole.log(calcTime('Bombay', '+5.5'));// get Singapore timeconsole.log(calcTime('Singapore', '+8'));// get London timeconsole.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 visiblevar options = { timeZone: 'UTC', timeZoneName: 'short' };console.log(date.toLocaleTimeString('en-US', options));// → "3:00:00 AM GMT"// sometimes even the US needs 24-hour timeconsole.log(date.toLocaleTimeString('en-US', { hour12: false }));// → "19:00:00"// show only hours and minutes, use options with the default locale - use an empty arrayconsole.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){&nbsp; &nbsp; var date = date.split(', ')[0].split('/');&nbsp; &nbsp; var time = date.split(', ')[1].split(':');&nbsp; &nbsp; return date[2]+'-'+date[0]+'-'+date[1]+'T'+time[0]+':'+time[1]+':'+time[2];}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript