Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ParsonsProjects/0ba895df4a8072b7c1ec58bbe1a0d25e to your computer and use it in GitHub Desktop.
Save ParsonsProjects/0ba895df4a8072b7c1ec58bbe1a0d25e to your computer and use it in GitHub Desktop.
Moment JS Countdown Clock
<div id="clock"></div>
window.onload = function(e){
var $clock = $('#clock'),
eventTime = moment('27-11-2020 08:30:00', 'DD-MM-YYYY HH:mm:ss').unix(),
currentTime = moment().unix(),
diffTime = eventTime - currentTime,
duration = moment.duration(diffTime * 1000, 'milliseconds'),
interval = 1000;
// if time to countdown
if(diffTime > 0) {
// Show clock
// $clock.show();
var $d = $('<div class="days" ></div>').appendTo($clock),
$h = $('<div class="hours" ></div>').appendTo($clock),
$m = $('<div class="minutes" ></div>').appendTo($clock),
$s = $('<div class="seconds" ></div>').appendTo($clock);
setInterval(function(){
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
var d = moment.duration(duration).days(),
h = moment.duration(duration).hours(),
m = moment.duration(duration).minutes(),
s = moment.duration(duration).seconds();
d = $.trim(d).length === 1 ? '0' + d : d;
h = $.trim(h).length === 1 ? '0' + h : h;
m = $.trim(m).length === 1 ? '0' + m : m;
s = $.trim(s).length === 1 ? '0' + s : s;
// show how many hours, minutes and seconds are left
$d.text(d);
$h.text(h);
$m.text(m);
$s.text(s);
}, interval);
}
};
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment