Javascript countdown using server-side time to complete - javascript

I am using this script to countdown and it works.
<script type="text/javascript">
(function (e) {
e.fn.countdown = function (t, n) {
function i() {
eventDate = Date.parse(r.date) / 1e3;
currentDate = Math.floor(e.now() / 1e3);
if (eventDate <= currentDate) {
n.call(this);
clearInterval(interval)
}
seconds = eventDate - currentDate;
days = Math.floor(seconds / 86400);
seconds -= days * 60 * 60 * 24;
hours = Math.floor(seconds / 3600);
seconds -= hours * 60 * 60;
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
days == 1 ? thisEl.find(".timeRefDays").text("day") : thisEl.find(".timeRefDays").text("day");
hours == 1 ? thisEl.find(".timeRefHours").text("hours") : thisEl.find(".timeRefHours").text("hours");
minutes == 1 ? thisEl.find(".timeRefMinutes").text("Minutes") : thisEl.find(".timeRefMinutes").text("Minutes");
seconds == 1 ? thisEl.find(".timeRefSeconds").text("Seconds") : thisEl.find(".timeRefSeconds").text("Seconds");
if (r["format"] == "on") {
days = String(days).length >= 2 ? days : "0" + days;
hours = String(hours).length >= 2 ? hours : "0" + hours;
minutes = String(minutes).length >= 2 ? minutes : "0" + minutes;
seconds = String(seconds).length >= 2 ? seconds : "0" + seconds
}
if (!isNaN(eventDate)) {
thisEl.find(".days").text(days);
thisEl.find(".hours").text(hours);
thisEl.find(".minutes").text(minutes);
thisEl.find(".seconds").text(seconds)
} else {
alert("Invalid date. Example: 30 Tuesday 2013 15:50:00");
clearInterval(interval)
}
}
thisEl = e(this);
var r = {
date: null,
format: null
};
t && e.extend(r, t);
i();
interval = setInterval(i, 1e3)
}
})(jQuery);
$(document).ready(function () {
function e() {
var e = new Date;
e.setDate(e.getDate() + 60);
dd = e.getDate();
mm = e.getMonth() + 1;
y = e.getFullYear();
futureFormattedDate = mm + "/" + dd + "/" + y;
return futureFormattedDate
}
$("#countdown").countdown({
date: "<?php echo $newcounter ?> ", // Change this to your desired date to countdown to
format: "on"
});
});
</script>
This script uses my client date, but i want use my server date. How can read the date read from my server? I tried this code in my script:
currentDate = <?php echo time() ?>;
but my countdown stops and does not work.

You have the server time. You are going about this correctly - no need to use AJAX. I think your problem involves the format of the date you ae passing to the countdown function. The countdown appears to want a number (newcounter = number milliseconds to wait?), but you are passing a timestamp (<?php echo time() ?>).
See #APAD1 comment above.

<?php
date_default_timezone_set('Europe/Vienna');
$now = new DateTime();
$dateJsFormat = $now->format('Y') .',' . ($now->format('m')-1) .','.$now->format('d') .',' . $now->format('H') .','.$now->format('i');
?>
<script>
var date = new Date(<?= $dateJsFormat ?>);
alert(date);
</script>
The JS-Date Object expects this format as parameters:
new Date(Year, Month, day, hour, minute) // JS-Code
The Month must be decremented by 1:
$now->format('m')-1 // see php-code above
In your example, you have to set this:
$("#countdown").countdown({
date: "<?= dateJsFormat ?>", // Change this to your desired date to countdown to
format: "on"
});
Hope this helps.

Related

24 hour countdown script that hits 00:00 every day at 11:00

I need a 24 hour countdown on my website that resets every day at 11:00 and after that starts 24 hour cycle again.
I don't need this script to control anything, I just need it to be there for visitors to see, so when they visit for example at 10:00 the will see 1 hour left on the clock and live counting down in format: Hours, Minutes, Seconds
And I need it to ignore clients time zone.
I found similar answer, but there is 1 hour window and it resets after that, I need it to reset immediately, how can I edit it to meet my requirements?
Here's what I found (this count to 21:00 then one hour window and than starts again):
var date;
var display = document.getElementById('time');
$(document).ready(function() {
getTime('GMT', function(time){
date = new Date(time);
});
});
setInterval(function() {
date = new Date(date.getTime() + 1000);
var currenthours = date.getHours();
var hours;
var minutes;
var seconds;
if (currenthours != 21){
if (currenthours < 21) {
hours = 20 - currenthours;
} else {
hours = 21 + (24 - currenthours);
}
minutes = 60 - date.getMinutes();
seconds = 60 - date.getSeconds();
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
display.innerHTML = hours + ':' + minutes + ':' +seconds;
} else {
display.innerHTML = 'LIVE NOW';
}
}, 1000);
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
I guess that 1 hour reset is due to validating hours alone. Try the following code:
var date;
var display = document.getElementById('time');
$(document).ready(function() {
getTime('GMT', function(time){
date = new Date(time);
});
});
setInterval(function() {
date = new Date(date.getTime() + 1000);
var currenthours = date.getHours();
var currentSecs = date.getSeconds();
var hours;
var minutes;
var seconds;
if (currenthours == 23 && currentsecs == 0){
display.innerHTML = 'LIVE NOW';
} else {
if (currenthours < 23) {
hours = 22 - currenthours;
} else {
hours = 23;
}
minutes = 60 - date.getMinutes();
seconds = 60 - date.getSeconds();
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
display.innerHTML = hours + ':' + minutes + ':' +seconds;
}
}, 1000);
To get accurate day duration even during daylight saving time changes you should stick to date arithmetic.
function time() {
var d1 = new Date();
var d2 = Date.UTC(d1.getUTCFullYear(),
d1.getUTCMonth(),
d1.getUTCDate() + (d1.getUTCHours() < 11 ? 0 : 1),
11);
var dh = d2 - d1;
var hours = Math.floor(dh / 3600000);
var dm = dh - 3600000 * hours;
var min = Math.floor(dm / 60000);
var ds = dm - 60000 * min;
var sec = Math.floor(ds / 1000);
var dmilli = ds - 1000 * sec;
setTimeout(time, dmilli);
hours = ('0' + hours).slice(-2);
min = ('0' + min).slice(-2);
sec = ('0' + sec).slice(-2);
document.querySelector('#the-final-countdown p').innerHTML = hours + ':' + min + ':' + sec;
}
time();

Javascript Countdown to show/hide on specified days & hours

Hi I've been trying to take and work with some code that I can get partially working, I want a countdown that we can set an end time it counts down to (obvious is obvious out of the way), we also want to set it to show at only certain times of the day and only certain days of the week.
I've managed to get the below working so we can set a time of the day to show but I can't get it to work so it only shows on the certain specified days. Can anyone help please?
var countdownMessage = "This ends in";
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var countdownEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 59); // countdownEnd 0000 hrs
//////////////////////////* Countdown *///////////////////////////////
function getSeconds() {
var ft = countdownEnd.getTime() + 86400000; // add one day
var diff = ft - time;
diff = parseInt(diff / 1000);
if (diff > 86400) {
diff = diff - 86400
}
startTimer(diff);
}
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
//getSeconds(); // and start again if required
}
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
var result = ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = (countdownMessage) + " " + result;
}
///////////////* Display at certain time of the day *//////////////////
//gets the current time.
var d = new Date();
if (d.getHours() >= 7 && d.getHours() <= 15) {
$("#countdown").show();
} else {
$("#countdown").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="getSeconds()">
<span id="countdown" style="font-weight: bold;"></span>
</body>
[EDIT]
Just to add to this I tried changing part of the script to this but it didn't work:
$(function() {
$("#countdown").datepicker(
{ beforeShowDay: function(day) {
var day = day.getDay();
if (day == 1 || day == 2) {
//gets the current time.
var d = new Date();
if(d.getHours() >= 7 && d.getHours() <= 10 ){
$("#countdown").show();
}
else {
$("#countdown").hide();
}
} else {
$("#countdown").hide();
}
}
});
});
Whatever you did is all good except the setInterval part where you are passing the string value as setInterval("tick()", 1000) instead of a function reference as setInterval(tick, 1000)
Also, I have updated the code as below to check the specific day along with specific hours which you had,
var d = new Date();
var day = d.getDay();
if (day == 0 || day == 6) {
if (d.getHours() >= 0 && d.getHours() <= 8) {
$("#countdown").show();
} else {
$("#countdown").hide();
}
}
You can give a try below,
var countdownMessage = "This ends in";
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var countdownEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 59); // countdownEnd 0000 hrs
//////////////////////////* Countdown *///////////////////////////////
function getSeconds() {
var ft = countdownEnd.getTime() + 86400000; // add one day
var diff = ft - time;
diff = parseInt(diff / 1000);
if (diff > 86400) {
diff = diff - 86400
}
startTimer(diff);
}
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval(tick, 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
//getSeconds(); // and start again if required
}
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
var result = ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = (countdownMessage) + " " + result;
}
$("#countdown").hide();
///////////////* Display at certain time of the day *//////////////////
//gets the current time.
var d = new Date();
var day = d.getDay();
if (day == 0 || day == 6) {
if (d.getHours() >= 0 && d.getHours() <= 8) {
$("#countdown").show();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="getSeconds()">
<span id="countdown" style="font-weight: bold;"></span>
</body>

Countdown Timer Problems

I have been looking for a count down timer on google and can't seem to find one.
I was just wondering if anyone would be able to help.
I got given one but it displays the wrong times.
I want it to display days, hours, minutes and seconds left.
heres what I need the timer on
http://pastebin.com/fQjyRFXw
It already has the timer code there but it's all wrong, any help would be great, thank you
If it's helps here's a snippet of the Java code
var count = <?= $time['a_time'] ?>;
var counter = setInterval(timer, 1000); //1000 will* run it every 1 second
function timer() {
count = count - 1;
if(count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("clock").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left";
}
Ok I see your problem. The a_time stored in database is an Unix timestamp, thus when you are counting down, you need to know how long is between now and a_time instead of only a_time.
Try this:
var count = <?= $time['a_time'] ?>;
var now = Math.floor(new Date().getTime() / 1000);
count = count - now;
var counter = setInterval(timer, 1000); //1000 will* run it every 1 second
function timer() {
count = count - 1;
if(count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
minutes %= 60;
hours %= 24;
document.getElementById("clock").innerHTML = days + "days " + hours + "hours " + minutes + "minutes and " + seconds + " seconds left";
}
Why not use one of the man examples on codepen such as this beautiful one
http://codepen.io/anon/pen/VeLWdz ?
(function (e) {
e.fn.countdown = function (t, n) {
function i() {
eventDate = Date.parse(r.date) / 1e3;
currentDate = Math.floor(e.now() / 1e3);
if (eventDate <= currentDate) {
n.call(this);
clearInterval(interval)
}
seconds = eventDate - currentDate;
days = Math.floor(seconds / 86400);
seconds -= days * 60 * 60 * 24;
hours = Math.floor(seconds / 3600);
seconds -= hours * 60 * 60;
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
days == 1 ? thisEl.find(".timeRefDays").text("day") : thisEl.find(".timeRefDays").text("days");
hours == 1 ? thisEl.find(".timeRefHours").text("hour") : thisEl.find(".timeRefHours").text("hours");
minutes == 1 ? thisEl.find(".timeRefMinutes").text("minute") : thisEl.find(".timeRefMinutes").text("minutes");
seconds == 1 ? thisEl.find(".timeRefSeconds").text("second") : thisEl.find(".timeRefSeconds").text("seconds");
if (r["format"] == "on") {
days = String(days).length >= 2 ? days : "0" + days;
hours = String(hours).length >= 2 ? hours : "0" + hours;
minutes = String(minutes).length >= 2 ? minutes : "0" + minutes;
seconds = String(seconds).length >= 2 ? seconds : "0" + seconds
}
if (!isNaN(eventDate)) {
thisEl.find(".days").text(days);
thisEl.find(".hours").text(hours);
thisEl.find(".minutes").text(minutes);
thisEl.find(".seconds").text(seconds)
} else {
alert("Invalid date. Example: 30 Tuesday 2013 15:50:00");
clearInterval(interval)
}
}
var thisEl = e(this);
var r = {
date: null,
format: null
};
t && e.extend(r, t);
i();
interval = setInterval(i, 1e3)
}
})(jQuery);
$(document).ready(function () {
function e() {
var e = new Date;
e.setDate(e.getDate() + 60);
dd = e.getDate();
mm = e.getMonth() + 1;
y = e.getFullYear();
futureFormattedDate = mm + "/" + dd + "/" + y;
return futureFormattedDate
}
$("#countdown").countdown({
date: "1 April 2017 09:00:00", // Change this to your desired date to countdown to
format: "on"
});
});

Adding UTC time to my countdown timer

I recently was searching after a countdown script that count down to a specific day, hour and minute and reset again after it reached the time.
Now a week later i see a major issue in the script. The countdown is based on local time and this is a problem.
I want to have the countdown based on the UTC time and not the local pc time.
Anyone that can help me with this because i'm not sure how to do this. I made also a clock script that i use and there i could say ".getUTC..." but i have no idea how to implement that in this script because i picked it up from the internet.
I'm not very good in javascript/jquery and i'm still learning a lot. I can mostely understand the scripts but i miss the lack of writing it myself so it would be very nice if you could edit the script so it's based on the UTC time and tell me a bit about it so i can learn from it. I really would appriciate that !
Thanks a lot,
Jens
var EVENTDAY = 1; // monday
var EVENTHOUR = 22; //
var EVENTMINUTE = 42; //
function getRemaining( now )
{
if ( now == null ) now = new Date();
var dow = now.getDay();
// the "hour" for now must include fractional parts of the hour, so...
var hour = now.getHours() + now.getMinutes()/60 + now.getSeconds()/3600;
// how many days from current day until event day?
var offset = EVENTDAY - dow;
// if event day is past *OR* if today is the event day but the event time is past...
if ( offset < 0 || ( offset == 0 && EVENTHOUR < hour ) )
{
// we are past the event time in current week, so
// target EVENTDAY is next week:
offset += 7;
}
// so this date (day of the month) is the next occurrence of the event:
var eventDate = now.getDate() + offset;
// and so then next occurrence of the event is at this time:
var eventTime = new Date( now.getFullYear(), now.getMonth(), eventDate,
EVENTHOUR, EVENTMINUTE, 0 );
// this is how many milliseconds from now to the next event occurrence
var millis = eventTime.getTime() - now.getTime();
// convert milliseconds to days/hours/minutes/seconds:
var seconds = Math.round( millis / 1000 );
var minutes = Math.floor( seconds / 60 );
seconds %= 60;
var hours = Math.floor( minutes / 60);
minutes %= 60;
var days = Math.floor( hours / 24 );
hours %= 24;
if ( seconds < 10 ) seconds = "0" + seconds;
if ( minutes < 10 ) minutes = "0" + minutes;
if ( hours < 10 ) hours = "0" + hours;
if ( days == 1 ) {
days = days + " day, ";
}
else {
days = days + " days, ";
}
// and return that formatted pretty:
return days + hours + ":" + minutes + ":" + seconds;
}
function tick()
{
// this is the automatic once a second display:
document.getElementById("countdown").innerHTML = getRemaining();
}
setInterval( tick, 1000 ); // specifies once a second
// here is a demo that allows you to test the function
// by specifying a date and time in the <form> below
function demo( form )
{
var t = form.theDate.value.split("/");
var mn = Number(t[0]);
var dy = Number(t[1]);
var yr = Number(t[2]);
var t = form.theTime.value.split(":");
var hr = Number(t[0]);
var mi = Number(t[1]);
var sc = Number(t[2]);
// so this is the test date/time that you specified:
var test = new Date( yr, mn-1, dy, hr, mi, sc );
// and here we call the master function and put its answer in the <form>:
form.remaining.value = getRemaining( test );
}
using Jcounter
Change line 34 in the jquery.jCounter-0.1.4.js file
serverDateSource: '/pathtofile/dateandtime.php', //path to dateandtime.php file (i.e. http://my-domain.com/dateandtime.php)
in the dateandtime.php file
<?php
ini_set('display_errors', 0); error_reporting(E_ALL);
date_default_timezone_set("Pacific/Auckland"); // CHANGE HERE
// GMT +12
if (isset($_GET['timezone'])) {
$timezone = new DateTimeZone($_GET['timezone']);
} else {
$timezone = new DateTimeZone("Pacific/Auckland");//CHANGE HERE
}
$date = new DateTime();
$date->setTimezone($timezone);
$dateAndTime = array("currentDate"=>$date->format('d F Y H:i:s'));
echo $_GET['callback'] . '(' . json_encode($dateAndTime) . ')';
?>
Then in you countdown timer file have it setup something like this:
<?php
date_default_timezone_set("Pacific/Auckland");//GMT+12 <--- CHANGE THIS
//Set your date and time below.
$day = date("D");
$hour = date("H");
if ($day=="Sun" && $hour>='9') {$date = date('d F Y H:i:s', strtotime('next Sunday 09:00:00'));}
else {$date = date('d F Y H:i:s', strtotime('this Sunday 09:00:00'));}
?>
<script type="text/javascript">
$(document).ready(function() {
$(".mycountdownname").jCounter({
animation: "slide",
date: "<?=$date?>", //format: DD month YYYY HH:MM:SS
timezone: "Pacific/Auckland",
format: "dd:hh:mm:ss",
twoDigits: 'on',
callback: function() { console.log("Event Ended!") }
});
});
</script>
<div class="mycountdownname">
<div class="countdown-theme">
<ul>
<li><p><span><em><b class="days">00</b><i class="daysSlider"><u>00</u><u>00</u></i></em>DAYS</span></p></li>
<li><p><span><em><b class="hours">00</b><i class="hoursSlider"><u>00</u><u>00</u></i></em>HOURS</span></p></li>
<li><p><span><em><b class="minutes">00</b><i class="minutesSlider"><u>00</u><u>00</u></i></em>MINS</span></p></li>
<li><p><span><em><b class="seconds">00</b><i class="secondsSlider"><u>00</u><u>00</u></i></em>SECS</span></p></li>
</ul>
<div class="jC-clear"></div><br>
<div class="jC-clear"></div>
</div>
</div>
You are already using Date here:
if ( now == null ) now = new Date();
You are almost there. Let's see some useful functions.
new Date().getTime()
will return the utc time.
new Date().toUTCString()
returns a string representation of the UTC timestamp.
new Date().getTimezoneOffset()
returns the number of minutes to be added to get the UTC value. So, this is how you can get the UTC timestamp:
foo.setHours(foo.getHours() + (foo.getTimezoneOffset() / 60)).getTimezoneOffset()
where foo is a Date object.
So, this is how you get the UTC value of a date:
function getUTCDate(input) {
return input.setHours(input.getHours() + (input.getTimezoneOffset() / 60)).getTimezoneOffset();
}
This is how you use it:
var now = getUTCDate(new Date());

Javascript Count Up Timer

I am trying to make a javascript timer that when initiated, starts counting up. The timer is just a visual reference from when a start button is clicked to when the end button is clicked.
I found a plugin online which works perfectly for counting down but I am trying to modify it to count up.
I hard coded a date way in the future. I am now trying to get the timer to start counting up to that date. This will be reset every time the start button is clicked.
This is the function I am working with. it works perfectly to count down but I cant figure out how to reverse it.
I thought it was something with how the differece was calculated but I believe it actually happens in the //calculate dates section.
Is there an easy way to reverse this math and have it count up instead?
Fiddle: http://jsfiddle.net/xzjoxehj/
var currentDate = function () {
// get client's current date
var date = new Date();
// turn date to utc
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
// set new Date object
var new_date = new Date(utc + (3600000*settings.offset))
return new_date;
};
function countdown () {
var target_date = new Date('12/31/2020 12:00:00'), // Count up to this date
current_date = currentDate(); // get fixed current date
// difference of dates
var difference = current_date - target_date;
// if difference is negative than it's pass the target date
if (difference > 0) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
//
};
// start
var interval = setInterval(countdown, 1000);
};
JSFiddle
var original_date = currentDate();
var target_date = new Date('12/31/2020 12:00:00'); // Count up to this date
var interval;
function resetCountdown() {
original_date = currentDate();
}
function stopCountdown() {
clearInterval(interval);
}
function countdown () {
var current_date = currentDate(); // get fixed current date
// difference of dates
var difference = current_date - original_date;
if (current_date >= target_date) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
//
};
// start
interval = setInterval(countdown, 1000);
};
This OP already has an answer but that has issue with timezone , so this answer.
DownVoters care to comment.
Try this. Fiddle
var TargetDate = new Date('2015', '08', '04', 11, 11, 30) // second parameter is month and it is from from 0-11
$('#spanTargetDate').text(TargetDate);
$('#spanStartDate').text(new Date());
var Sec = 0,
Min = 0,
Hour = 0,
Days = 0;
var counter = setInterval(function () {
var CurrentDate = new Date()
$('#spanCurrentDate').text(CurrentDate);
var Diff = TargetDate - CurrentDate;
if (Diff < 0) {
clearInterval(counter);
$('#timer').text('Target Time Expired. test in fiddle')
} else {
++Sec;
if (Sec == 59) {
++Min;
Sec = 0;
}
if (Min == 59) {
++Hour;
Min = 0;
}
if (Hour == 24) {
++Days;
Hour = 0;
}
if (Sec <= Diff) $('#timer').text(pad(Days) + " : " + pad(Hour) + " : " + pad(Min) + " : " + pad(Sec));
}
}, 1000);
function pad(number) {
if (number <= 9) {
number = ("0" + number).slice(-4);
}
return number;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Target Time - <span id="spanTargetDate"></span>
<br/>
<br/>Start Time - <span id="spanStartDate"></span>
<br/>
<br/>Current Time - <span id="spanCurrentDate"></span>
<br/>
<br/>Timer (DD:HH:MM:SS) - <span id="timer"></span>
<br/>
<br/>

Categories