首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用moment和moment-timezone计算事件发生前的剩余秒数

使用moment和moment-timezone计算事件发生前的剩余秒数
EN

Stack Overflow用户
提问于 2016-10-18 12:26:25
回答 1查看 752关注 0票数 0

我正在为一个事件创建倒计时,服务器会告诉我离这个事件还剩多少秒。它在相同的时区America/New_York运行良好,但我不确定如何在不同的时区实现这一点。我想我必须根据用户的时区添加/减去一些秒数。我考虑到服务器返回的秒数将始终以EST为单位。有人能给点建议吗?到目前为止,我得到了这个,但我得到了一个错误:

代码语言:javascript
复制
let serverZoneTime = new moment().tz.zone("America/New_York").offset(now); 
let currentZoneTime = moment.tz.guess().offset(now);

console.log((EstTzOffset - currentTz));
EN

回答 1

Stack Overflow用户

发布于 2018-03-01 22:17:27

首先,如果这是某一天下午6点的事件,我将获得该事件开始时间的确切时间戳或UTC时间。下面我使用了一个假的时间戳。

这一点很重要,因为观看活动的人可能会在活动当天的"now“(上面使用的)和下午6点之间从EST更改为DST。

听起来你已经让倒计时工作了,但这只是你正在处理的时区问题,所以我将跳过倒计时逻辑。

代码语言:javascript
复制
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');

对于倒计时,您现在也需要时间,它遵循与上面相同的逻辑:

代码语言:javascript
复制
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()函数来重复每一秒。

代码语言:javascript
复制
const millisecondsToEvent = userEventTimestamp - userNowtimestamp;
const secondsToEvent = millisecondsToEvent / 1000;

希望这对某些人有用(刚刚意识到这是两年前的事了)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40099499

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档