我正在为一个事件创建倒计时,服务器会告诉我离这个事件还剩多少秒。它在相同的时区America/New_York运行良好,但我不确定如何在不同的时区实现这一点。我想我必须根据用户的时区添加/减去一些秒数。我考虑到服务器返回的秒数将始终以EST为单位。有人能给点建议吗?到目前为止,我得到了这个,但我得到了一个错误:
let serverZoneTime = new moment().tz.zone("America/New_York").offset(now);
let currentZoneTime = moment.tz.guess().offset(now);
console.log((EstTzOffset - currentTz));发布于 2018-03-01 22:17:27
首先,如果这是某一天下午6点的事件,我将获得该事件开始时间的确切时间戳或UTC时间。下面我使用了一个假的时间戳。
这一点很重要,因为观看活动的人可能会在活动当天的"now“(上面使用的)和下午6点之间从EST更改为DST。
听起来你已经让倒计时工作了,但这只是你正在处理的时区问题,所以我将跳过倒计时逻辑。
const moment = require('moment-timezone');
// Get User's Timezone
const userTimezone = moment.tz.guess(); // this has to be on the client not server
const serverTimezone = "America/New_York";
// Get the exact timestamp of the event date apply the server timezone to it.
const serverEventTime = moment(34534534534, 'x').tz(serverTimezone);
// Take the server time and convert it to the users time
const userEventTime = serverEventTime.clone().tz(userTimezone);
// From here you can format the time however you want
const formattedUserEventTime = userEventTime.format('YYYY-MM-DD HH:mm:ss');
// Or format to a timestamp
const userEventTimestamp = userEventTime.format('x');对于倒计时,您现在也需要时间,它遵循与上面相同的逻辑:
const serverTimeNow = moment().tz(serverTimezone);
const userTimeNow = serverTimeNow.clone().tz(userTimezone);
// Get timestamp so we can do easier math with the time
const userNowTimestamp = userTimeNow.format('x');现在我们要做的就是从事件时间中减去time来得到差值,然后使用一个setInterval()函数来重复每一秒。
const millisecondsToEvent = userEventTimestamp - userNowtimestamp;
const secondsToEvent = millisecondsToEvent / 1000;希望这对某些人有用(刚刚意识到这是两年前的事了)。
https://stackoverflow.com/questions/40099499
复制相似问题