SHT
SHT

Reputation: 720

MomentJS - How to show remaining time

I have a competition-module and when I post the competition, there is a deadline for when the competition ends. My API JSON returns an enddate. I want to use the MomentJS plugin and so far i have simply added:

<script src="/js/moment.min.js"></script>

and my html:

<time class="newstime" datetime="2014-08-04T10:00:00.000Z">//DISPLAY REMAINING TIME HERE</time>

How do I achieve that it displays the remaining time?

thanks in advance

Upvotes: 2

Views: 7838

Answers (2)

moldovean
moldovean

Reputation: 3261

you can do your own by creating a function that refreshes itself every second:

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>

where in our case d2 is an arbitrary future date. Don't forget months in js are counted from 0, not one. so 7 = August (not July)

var d2 = new Date(2016, 7, 3, 18, 0,0,0);

hope it's clear.

Upvotes: 1

Rachel Gallen
Rachel Gallen

Reputation: 28553

There is a plugin for this called Moment-countdown It can be localixzed using bitbucket

here is a piece of code from 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

Upvotes: 7

Related Questions