【问题标题】:MomentJS - How to show remaining timeMomentJS - 如何显示剩余时间
【发布时间】:2014-08-14 10:18:01
【问题描述】:
我有一个competition-module,当我发布比赛时,比赛结束时有一个截止日期。我的 API JSON 返回一个结束日期。我想使用MomentJS 插件,到目前为止我只是添加了:
<script src="/js/moment.min.js"></script>
还有我的html:
<time class="newstime" datetime="2014-08-04T10:00:00.000Z">//DISPLAY REMAINING TIME HERE</time>
如何实现显示剩余时间?
提前致谢
【问题讨论】:
标签:
javascript
html
momentjs
【解决方案1】:
有一个名为Moment-countdown的插件可以使用bitbucket进行本地化
这是来自 git hub 的一段代码
//from then until now
moment("1982-5-25").countdown().toString(); //=> '30 years, 10 months, 14 days, 1 hour, 8 minutes, and 14 seconds'
//accepts a moment, JS Date, or anything parsable by the Date constructor
moment("1955-8-21").countdown("1982-5-25").toString(); //=> '26 years, 9 months, and 4 days'
//also works with the args flipped, like diff()
moment("1982-5-25").countdown("1955-8-21").toString(); //=> '26 years, 9 months, and 4 days'
//accepts all of countdown's options
moment().countdown("1982-5-25", countdown.MONTHS|countdown.WEEKS, NaN, 2).toString(); //=> '370 months
【解决方案2】:
您可以自己创建一个每秒刷新一次的函数:
var t=setInterval(runFunction,1000);
function runFunction(){
var d = new Date();
var d2 = new Date(2016, 7, 3, 18, 0,0,0);
var milSec = d2-d;
var d3 = new Date(milSec);
nrDays = (Math.floor(d3/1000/60/60/24));
nrHours = (Math.floor(d3/1000/60/60))%24;
nrMin = (Math.floor(d3/1000/60))%60;
nrSec = (Math.floor(d3/1000))%60;
document.getElementById("countdown").innerHTML = nrDays +" days: " + nrHours+" hours: "+ nrMin + " min " + nrSec +" sec";
}
<!DOCTYPE html>
<html>
<body>
<p id="countdown">here</p>
</body>
</html>
在我们的例子中,d2 是一个任意的未来日期。不要忘记 js 中的月份是从 0 开始计算的,而不是从 1 开始计算的。所以 7 = 八月(不是七月)
var d2 = new Date(2016, 7, 3, 18, 0,0,0);
希望很清楚。