【问题标题】:Moment countdown to a date日期倒计时时刻
【发布时间】:2017-02-21 08:48:21
【问题描述】:

我有 2 个日期要从一个日期倒数到另一个日期。我正在使用时刻库​​。我找到了this answer here,但它没有给我正确的结果。

下面的代码给了我下面的时间:

var eventTime =  new Date(startTime);
var currentTime =  new Date();

console.log(eventTime);
console.log(currentTime);

2017 年 2 月 24 日星期五 19:45:00 GMT+0000 (GMT) --> eventTime

2017 年 2 月 21 日星期二 08:42:42 GMT+0000 (GMT) --> currentTime

我尝试了以下多种,但无法显示正确的倒计时。

var eventTime = new Date('2017-02-24T19:45:00.000000+0000').getTime();
var currentTime = new Date().getTime()

console.log(eventTime);
console.log(currentTime)

var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime * 1000, 'milliseconds');
var interval = 1000;

setInterval(function() {
  duration = moment.duration(duration - interval, 'milliseconds');
  console.log(duration.days() + ':' + duration.hours() + ":" + duration.minutes() + ":" + duration.seconds())
}, interval);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>

【问题讨论】:

  • @VincenzoC 单击运行代码 sn-p 多次,您将看到该值不断变化且不一致……例如,它目前表示该事件对我来说还有 29 天。 .. 我猜我在获取 ms 或类似的东西时出错了

标签: javascript time momentjs


【解决方案1】:

.getTime() 已经返回毫秒,不需要乘以 1000。

你必须把这一行改成这样

var duration = moment.duration(diffTime * 1000, 'milliseconds');

到这里

var duration = moment.duration(diffTime, 'milliseconds');

【讨论】:

    猜你喜欢
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 2013-05-24
    相关资源
    最近更新 更多