What I'd like to accomplish is a countdown that updates live... like this:
6 Days (just the days)
12 Hours (just hours within 1 day)
59 Minutes (just minutes within 1 hour)
59 Seconds (just seconds within 1 minute)
Best way to accomplish this?
You can find a working example at http://jsfiddle.net/gaby/QH6X8/79/
var end = new Date('15 Dec 2010');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24
var timer;
function showRemaining()
{
var now = new Date();
var distance = end - now;
if (distance < 0 ) {
// handle expiry here..
clearInterval( timer ); // stop the timer from continuing ..
alert('Expired'); // alert a message that the timer has expired..
}
var days = Math.floor(distance / _day);
var hours = Math.floor( (distance % _day ) / _hour );
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var countdownElement = document.getElementById('countdown');
countdownElement.innerHTML = 'Days: ' + days + '<br />';
countdownElement.innerHTML += 'Hours: ' + hours+ '<br />';
countdownElement.innerHTML += 'Minutes: ' + minutes+ '<br />';
countdownElement.innerHTML += 'Seconds: ' + seconds+ '<br />';
}
timer = setInterval(showRemaining, 1000);
jQuery Countdown plugin
here you can generate countdown timer if you like - just press generate and copy paste the results into .html file
http://www.ricocheting.com/code/javascript/html-generator/countdown-timer
Notable mention: http://www.littlewebthings.com/projects/countdown/
(probable irrelevant since you mentioned that you don't want to use a plugin)
The problem with the above accepted approach is that there will be issues here related to timezone differences and daylight saving time. See this question asked by me Javascript Countdown and Timezone and Daylight Saving Time Issues
jCounter offers control on what format you want your countdown to display among other control settings and methods.
Related
I have an issue in displaying counter between 2 dates. I know the issue and it is that Timezone is GMT+05:30
I need to know, how to rectify that
My Solution:
var start = new Date();
var end = new Date("2017-10-03"); // This date is coming from database as <?php echo $date_end; ?>
function getClock() {
var start = new Date();
var end = new Date("<?php echo $date_end; ?>");
var diff = Math.round((end.getTime() - start.getTime()) / 1000);
var hours = Math.floor(diff / 3600);
diff -= hours * 3600
var minutes = Math.floor(diff / 60);
diff -= minutes * 60;
var seconds = diff % 60;
if(document.getElementById('countdown')){
document.getElementById('countdown').innerHTML = "<span>"
+ hours + "</span> hours <span>" + minutes + "</span> minutes <span>"
+ seconds + "</span> seconds";
}
}
setInterval('getClock()', 1000);
As start date is 02 Oct 10PM and End date is 03 Oct. So as per time calculation i shall get timer of 2 hours
but i am getting timer is 2hours+5:30 = 7:30 hours.
Please help in getting right timer.
JS Fiddle link is HERE
You can get the timezone offset from the end date after you construct it, and then use that to reassign the value.
Here is a related question.
You can use the code from that post as follows:
var end = new Date("<?php echo $date_end; ?>");
end.setTime( end.getTime() + end.getTimezoneOffset()*60*1000 );
Try something like this.
setInterval(function(){
var start = new Date();
var end = new Date("2017-10-03 00:00:00");
var diff = Math.round((end.getTime() - start.getTime()) / 1000);
var hours = Math.floor(diff / 3600);
diff -= hours * 3600
var minutes = Math.floor(diff / 60);
diff -= minutes * 60;
var seconds = diff % 60;
if(document.getElementById('countdown')){
document.getElementById('countdown').innerHTML = "<span>"
+ hours + "</span> hours <span>" + minutes + "</span> minutes <span>"
+ seconds + "</span> seconds";
}
}, 1000);
The problem is because of the way Javascript handles timezones in the Date constructor (check out the documentation for details). If, instead of passing ("2017-10-03") you pass (2017, 9, 3), it should work. To avoid these kinds of problems, it is a good idea to always work in UTC.
Make sure you pass year, month and day separately to initialize the date, so the system timezone is used, same as when you initialize your start date:
var end_str = "<?php echo $date_end; ?>";
var arr = end_str.split("-")
arr = Date.new(arr[0], arr[1]-1, arr[2]); //month is 0-indexed
I have a working countdown timer "days, hours, minutes, seconds" and I need to change the color of the seconds "var" from white to yellow while the other var's will keep the white color.
The problem is that the whole countdown date is being placed on a single div and I cannot add a specific class or a span to the "seconds" variable.
I tried many different solutions but none seems to work in this case so I decided to ask for help and make a Question.
The HTML.
<div class="container">
<div id="countdown" align="center"> <!-- The countdown is being displayed here -->
</div>
</div>
The JS.
CountDownTimer('06/01/2016 06:00 AM', 'countdown');
function CountDownTimer(dt, id)
{
var end = new Date(dt);
var _second = 1000;
var _minute = + _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = 'end';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById('countdown').innerHTML = days + ' ';
document.getElementById('countdown').innerHTML += hours + ' ';
document.getElementById('countdown').innerHTML += minutes + ' ';
document.getElementById('countdown').innerHTML += seconds + ' ';
}
timer = setInterval(showRemaining, 1000);
}
Working JS FIDDLE here where you can see for yourself:
https://jsfiddle.net/baqc6nx2/1/
And here is the image explaining how the seconds var should be colored yellow and the others white.
Sorry for my bad English, and thank you for your time.
EDIT:---------------------------------------------------------------
This is not a duplicate, I know the last child selectors, but in this case it wont work, I tried.
Edit-----------------------------------------------------------------
TGO Helped me and now it is working, please reopen the question so I can complete it.
Here is an updated fiddle which solves your problem. http://jsfiddle.net/baqc6nx2/2
For convenience, this is the changed line of code:
document.getElementById('countdown').innerHTML += '<span style="color:yellow;">' + seconds + '</span> ';
Here I create a span tag, give it the proper CSS style to turn the color yellow, and the seconds value is put inside the span element.
I am trying to make a countdown timer that will countdown to a certain date and time.
I would like to be able to set the date and time from a 'admin panel' by typing in the date and time(ex 2014-01-25, 15:00) in a textbox or something similar.
As you might've figured, I'm not the best at PHP or JavaScript and I'm in need of directions as of how I would do this.
Any help is appreciated as I haven't made any progress in the last 2 hours I've tried doing this.
To do this with no frameworks like JQuery, you can do the following:
var MINUTE_IN_MILLISECONDS = 60 * 1000;
var HOUR_IN_MILLISECONDS = 60 * MINUTE_IN_MILLISECONDS;
var YEAR_IN_MILLISECONDS = 24 * HOUR_IN_MILLISECONDS;
var targetDate = new Date('2014-01-25 15:00');
var countdownInterval;
function countdown(){
var currentDate = new Date();
var difference = targetDate.getTime() - currentDate.getTime();
//Countdown has expired, cancel interval and do other tasks here
if(difference <= 0)
{
difference = 0;
clearInterval(countdownInterval);
//Update button here
}
var days = Math.floor(difference / YEAR_IN_MILLISECONDS);
difference -= days * YEAR_IN_MILLISECONDS;
var hours = Math.floor(difference / HOUR_IN_MILLISECONDS);
difference -= hours * HOUR_IN_MILLISECONDS;
var minutes = Math.floor(difference / MINUTE_IN_MILLISECONDS);
difference -= minutes * MINUTE_IN_MILLISECONDS;
var seconds = Math.floor(difference / 1000);
console.log(days + ":" + hours + ":" + minutes + ":" + seconds);
}
countdownInterval = setInterval(countdown, 1000);
Here's the Fiddle
Full demonstration: http://jsfiddle.net/DerekL/T48SL/
<form>
<input type="date" required><input type="time" required>
<input type="submit">
</form>
<span></span>
$("form").on("submit", function (e) {
e.preventDefault();
var date = $("input[type=date]").val(),
time = $("input[type=time]").val(),
targetTime = new Date(date + " " + time),
interval = setInterval(function () {
$("span").html(
(((+startingTime - Date.now()) / 1000)|0) + " seconds left until " + startingTime.toString() + "."
);
}, 500);
});
It is fairly easy to format the time instead of just seconds with Algebra:
//yourTime is in seconds
(yourTime) % 60 //seconds
(yourTime / 60 |0) % 60 //minutes
(yourTime / 3600 |0) % 24 //hours
(yourTime / 86400 |0) //days
/*
* Explanation:
* % is mod, it finds the remainder of two numbers.
* |0 is binary OR, it rounds down a floating number.
*
*/
With this technique, you do not need to do a bunch of subtraction and create a lot of junk variables in the process.
So, I have the below (seconds countdown) in good order. But! I am trying to add hours & minutes as apart of the count down as well. Ideally keeping the same structure, and just using pure JS. I would like the output to be:
There is X hours, X minutes, and X seconds remaining on this Sale!
var count=30;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
}
If the solution has to be a rewrite with jQuery or another library; that's fine. Just not preferable.
Cheers and Salutations for any help.
Something like this:
var count = 30;
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("timer").innerHTML = hours + "hours " + minutes + "minutes and" + seconds + " seconds left on this Sale!"; // watch for spelling
}
var totalSeconds = 3723; // lets say we have 3723 seconds on the countdown
// that's 1 hour, 2 minutes and 3 seconds.
var hours = Math.floor(totalSeconds / 3600 );
var minutes = Math.floor(totalSeconds % 3600 / 60);
var seconds = totalSeconds % 60;
var result = [hours, minutes, seconds].join(':');
console.log(result);
// 1:2:3
hours is seconds divided by the number of seconds in hour (3600) rounded down
minutes is the remainder of the above division, divided by the number of seconds in a minute (60), rounded down.
seconds is the remainder of total seconds divided by seconds in a minute.
Each calculation after hour has to use a modulus calculation to get the remainder, because you don't care about total time at that step, just progress to the next tick.
I would use a similar method to the others, but I wouldn't rely on setInterval / setTimeout as a timer, especially if users might be looking at the page for some time, as it tends to be inaccurate.
var endTime = new Date(2013, 10, 31).getTime() / 1000;
function setClock() {
var elapsed = new Date().getTime() / 1000;
var totalSec = endTime - elapsed;
var d = parseInt( totalSec / 86400 );
var h = parseInt( totalSec / 3600 ) % 24;
var m = parseInt( totalSec / 60 ) % 60;
var s = parseInt(totalSec % 60, 10);
var result = d+ " days, " + h + " hours, " + m + " minutes and " + s + " seconds to go!";
document.getElementById('timeRemaining').innerHTML = result;
setTimeout(setClock, 1000);
}
setClock();
This method calculates the difference between now and the date in the future each time it is run, thus removing any inaccuracies.
Here is an example: http://jsfiddle.net/t6wUN/1/
In JavaScript I have a variable Time in milliseconds.
I would like to know if there is any build-in function to convert efficiently this value to Minutes:Seconds format.
If not could you please point me out a utility function.
Example:
FROM
462000 milliseconds
TO
7:42
Just create a Date object and pass the milliseconds as a parameter.
var date = new Date(milliseconds);
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
alert(((h * 60) + m) + ":" + s);
Thanks guys for your support, at th end I came up with this solution. I hope it can helps others.
Use:
var videoDuration = convertMillisecondsToDigitalClock(18050200).clock; // CONVERT DATE TO DIGITAL FORMAT
// CONVERT MILLISECONDS TO DIGITAL CLOCK FORMAT
function convertMillisecondsToDigitalClock(ms) {
hours = Math.floor(ms / 3600000), // 1 Hour = 36000 Milliseconds
minutes = Math.floor((ms % 3600000) / 60000), // 1 Minutes = 60000 Milliseconds
seconds = Math.floor(((ms % 360000) % 60000) / 1000) // 1 Second = 1000 Milliseconds
return {
hours : hours,
minutes : minutes,
seconds : seconds,
clock : hours + ":" + minutes + ":" + seconds
};
}
In case you already using Moment.js in your project, you can use the moment.duration function
You can use it like this
var mm = moment.duration(37250000);
console.log(mm.hours() + ':' + mm.minutes() + ':' + mm.seconds());
output: 10:20:50
See jsbin sample
It's easy to make the conversion oneself:
var t = 462000
parseInt(t / 1000 / 60) + ":" + (t / 1000 % 60)
You may like pretty-ms npm package: https://www.npmjs.com/package/pretty-ms
If that what you are searching. Headless nice formatting (time in the units that are needed as ms grow), personalisable, and cover different situations. Small and efficient for what it cover.
function msToMS(ms) {
var M = Math.floor(ms / 60000);
ms -= M * 60000;
var S = ms / 1000;
return M + ":" + S;
}