Countdown inverted - javascript

anyone can help me? Example, I want a countdown timer but inverted, example:
I insert my date and hour in javascript or mysqL (doesn't matter) and it will count ..
Example: I inserted: 01/07/2015
today the counter will show: 1day 1hour 19min

If you don't want to use jquery then you can do something like this:
var startTime = +new Date("07/01/2015"); // m/d/Y gets timestamp in ms
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var day = hour * 24;
var element = document.getElementById('timer'); // target element for the timer
function countUp() {
// time between now and the start date
var time = Date.now() - startTime;
// days passed since start
var days = Math.floor(time / day);
time -= days * day;
// hours passed
var hours = Math.floor(time / hour);
time -= hours * hour;
// minutes passed
var minutes = Math.floor(time / minute);
// update element
element.innerHTML = days + 'day ' + hours + 'hour ' + minutes + 'min';
setTimeout(countUp, minute);
};
countUp();
<span id="timer"></span>

Since you want to use the jQuery Countdown plugin, you can just use it's built-in count up functionality. Take a look at the 'Count Up' tab of the jQuery Countdown page: http://keith-wood.name/countdown.html.
EDIT: Adding code example
$("#countdown").countdown({since: new Date(2015, 7-1, 1)});
#countdown {
float: left;
width: 240px;
}
<link href="http://keith-wood.name/css/jquery.countdown.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://keith-wood.name/js/jquery.plugin.js"></script>
<script src="http://keith-wood.name/js/jquery.countdown.js"></script>
<span id="countdown">

Related

Creating a Custom Countdown Timer

I'm a graphic designer who has also been tasked with building a website for the church that I work for. I've built many websites in the past, so this isn't an issue at all, however, something that I'm looking to do with this site is to have as many elements that can just simply run on their own as possible. I'm a complete beginner when it comes to JavaScript, and honestly don't really have an idea at all about what I'm doing.
I'd like for the new site to have a custom countdown timer that will count down to when we go live, and then display a link for our live stream for a set period of time, and then reset. The code below shows what I've already managed to write from just searching around on the internet. The problem with it is that it relies on a person (which half of the time is a web-volunteer) to remember to change the date and time to the next service after the current service is finished, and 90% of the time they forget.
In a perfect world, I'd like for this countdown timer to automatically countdown to the nearest Tuesday at 6:00 pm, then show a link to our live stream for 20 minutes, then reset. Or if Sunday at 10:00 am comes first, countdown to Sunday at 10am, then show a link to our live stream for one hour and 15 minutes, and then reset. Theoretically I would imagine this could run indefinitely as it would just check for if Tuesday at 6pm comes first, or if Sunday at 10am comes first, then countdown to those times, pause, show some hyperlinked text, and then repeat.
I apologize if this has already been talked about here, I tried searching as thoroughly as I could and couldn't find anything.
Any help at all would be greatly appreciated.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p id="demo" class="countdown-live" style="text-align:center;"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date("October 20, 2020 18:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + " d " + hours + " h "
+ minutes + " m & " + seconds + " s";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = 'Watch Live!';
}
}, 1000);
</script>
</body>
</html>
This is a little delayed but here's something that works with a little maintenance.
(() => {
var currentDate = new Date();
currentDate = currentDate.toLocaleString("en-US", {
timeZone: "America/New_York"
});
// Service times
var serviceTEN = "2021/12/06 11:15";
var serviceTWELVE = "2021/12/06 13:45";
var serviceTWO = "2021/12/06 15:45";
var serviceFIVE = "2021/12/06 16:45";
var serviceSEVEN = "2021/12/06 19:45";
var waiting;
// Set current service
var currentService = serviceTEN;
function pad(num, size) {
var s = "0" + num;
return s.substr(s.length - size);
}
// Get the current time, set the correct timezone, and parse it to the same layout.
// Find the difference between the current date and the service time.
// Have that be the time remaining.
function getTimeRemaining(endtime) {
var now = new Date();
now = now.toLocaleString("en-US", {
timeZone: "America/New_York"
});
// Parse the date to find each variable (seconds, minutes, hours, days)
let t = Date.parse(endtime) - Date.parse(now);
let seconds = Math.floor((t / 1000) % 60);
let minutes = Math.floor((t / 1000 / 60) % 60);
let hours = Math.floor((t / (1000 * 60 * 60)) % 24);
let days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
total: t,
days: days,
hours: hours,
minutes: minutes,
seconds: seconds,
};
}
// the id refers to "js-clock" which is the beginning of the ID, this can be changed
function clock(id, endtime) {
let days = document.getElementById(id + "-days");
let hours = document.getElementById(id + "-hours");
let minutes = document.getElementById(id + "-minutes");
let seconds = document.getElementById(id + "-seconds");
let timeinterval = setInterval(function() {
let t = getTimeRemaining(endtime);
// Look through the service times and figure out which service it should be.
if (t.total <= 0) {
if (waiting === true) {
location.reload();
} else if (t.total < -300000) {
switch (endtime) {
case serviceTEN:
endtime = serviceTWELVE;
break;
case serviceTWELVE:
endtime = serviceTWO;
break;
case serviceTWO:
endtime = serviceFIVE;
break;
case serviceFIVE:
endtime = serviceSEVEN;
break;
default:
break;
}
} else {
clearInterval(timeinterval);
}
} else {
waiting = true;
// Edit the 2 or 3 to change amount of digits
days.innerHTML = pad(t.days, 3);
hours.innerHTML = pad(t.hours, 2);
minutes.innerHTML = pad(t.minutes, 2);
seconds.innerHTML = pad(t.seconds, 2);
}
}, 1000);
}
clock("js-clock", currentService);
})();
<div class="mainOverlayCountdown-k" id="mainOverlayCountdownID-k">
<h1 id="countdownHeader-k">Next service begins in:</h1>
<div class="countdown-cover">
<div id="js-clock" class="countdowntimer">
<div id="js-clock-days" class="clock-number">00</div>
<div class="clock-label">Days</div>
<div id="js-clock-hours" class="clock-number">00</div>
<div class="clock-label">Hrs</div>
<div id="js-clock-minutes" class="clock-number">00</div>
<div class="clock-label">Min</div>
<div id="js-clock-seconds" class="clock-number">00</div>
<div class="clock-label">Sec</div>
</div>
</div>
</div>
To change the service times, edit the service'TIME' Variables. You might have to play around with it to get the correct timezone.
to add/delete service times, but make sure you also add/delete it in the variables where you set the date, and the switch function.
Hope this helps!

jQuery Countdown get time until 10:00 am today or tomorrow

I need a little script and I am a little confused.
I want to use this plugin: http://keith-wood.name/countdown.html
Goal: Have a Countdown, that counts from now to 10:00 am - if it's 0-9:59:59 am count to 10 o'clock today if it's after 10:00:00 count to 10:00 tomorrow.
Is that understandable?
Here's what I need with javascript / jquery (this will not work, i know):
var currentDate = new Date(new Date().getTime());
var hours = currentDate.getHours();
var endTime;
if(hours >= 10){
endTime = give me next day 10:00
} else {
endTime = give me this day 10:00
}
$("#countdown").countdown({until: endTime, format: 'HMS'});
The following should work (console.log() was added for testing purposes). Beware that it will use the timezone of the browser instead of UTC time.
var currentDate = new Date(new Date().getTime());
var hours = currentDate.getHours();
var endTime = new Date(currentDate);
endTime.setMinutes(0);
endTime.setSeconds(0);
endTime.setHours(10);
if(hours >= 10){
endTime.setDate(endTime.getDate() + 1);
}
console.log(endTime);
$("#countdown").countdown({until: endTime, format: 'HMS'});
You can handle it this way.
currentDate.setHours(10,00,00);
if(hours >= 10){
endTime = currentDate.AddDays(1);
}
This is the function I use for my website:
function countDown(id, date = "Jan 5 2018") {
var int = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = date - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor( distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById(id).innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById(id).innerHTML = "00d 00h 00m 00s";
}
}, 1000);
return int;
}
In the date parameter, you need to enter your date and hour (ex. Jan 1, 2018 00:00:00) and in the id parameter the id selector (not '#myid' but only the name 'myid').
I hope this can be useful.
You can see it in action here
If you need the next day then increment the current date, then pass year, month, day and hours (static 10) to create the end date.
$(function() {
var currentDate = new Date();
var hours = currentDate.getHours();
var day;
if(hours >= 10){
day = currentDate.getDate() + 1;
} else {
day = currentDate.getDate();
}
var endTime = new Date(currentDate.getFullYear(), currentDate.getMonth(), day, 10);
$("#countdown").countdown({until: endTime, format: 'HMS'});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-countdown/2.0.2/jquery.plugin.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-countdown/2.0.2/jquery.countdown.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-countdown/2.0.2/jquery.countdown.min.css" />
<div id='countdown'></div>

How to add minutes and hours to a time string using jquery

I want to add 30 minutes and then one hour to my variable which i already have my own date
var initialDate = '10:00';
So
if (some condition){
// i add 30 minutes ->10:30
}elseif(another condition){
// i add 1hour ->11:00
}
I tried this but doesn't work
var initialDate = '10:00';
var theAdd = new Date(initialDate);
var finalDate = theAdd.setMinutes(theAdd.getMinutes() + 30);
If I understand you correctly, the following will help you.
You need to add momentjs dependency via script tag and you can Parse, validate, manipulate, and display dates in JavaScript.
You can find more documentation regarding this in momentjs website
console.log(moment.utc('10:00','hh:mm').add(1,'hour').format('hh:mm'));
console.log(moment.utc('10:00','hh:mm').add(30,'minutes').format('hh:mm'));
<script src="https://momentjs.com/downloads/moment-with-locales.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var theAdd = new Date();
// Set Hours, minutes, secons and miliseconds
theAdd.setHours(10, 00, 00, 000);
if (some condition) {
// add 30 minutes --> 10:30
theAdd.setMinutes(theAdd.getMinutes() + 30);
}
elseif (some condition) {
// add 1 hour --> 11:00
theAdd.setHours(theAdd.getHours() + 1);
}
Then you print the var theAdd to obtain the date and time.
To obtain just the time:
theAdd.getHours() + ":" + theAdd.getMinutes();
This should do the job. Dates need a year and month in their constructor, and you have to specify larger units of time if you specify and smaller ones, so it needs a day as well. Also, you have to pass in the hours and minutes separately. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date.
var initialDate = '10:00';
var theAdd = new Date(1900,0,1,initialDate.split(":")[0],initialDate.split(":")[1]);
if(30 min condition){
theAdd.setMinutes(theAdd.getMinutes() + 30);
} else if (1 hour condition){
theAdd.setHours(theAdd.getHours() + 1);
}
console.log(theAdd.getHours()+":"+theAdd.getMinutes());
Here is a javascript function that will add minutes to hh:mm time string.
function addMinutes(timeString, addMinutes) {
if (!timeString.match(/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/))
return null;
var timeSplit = timeString.split(':');
var hours = parseInt(timeSplit[0]);
var minutes = parseInt(timeSplit[1]) + parseInt(addMinutes);
hours += Math.floor(minutes / 60);
while (hours >= 24) {
hours -= 24;
}
minutes = minutes % 60;
return ('0' + hours).slice(-2) + ':' + ('0' +minutes).slice(-2);
}

Getting the difference between 2 dates in Javascript in hours, minutes, seconds with UTC

Like the title says, I need to get the difference between two dates and display the hours, minutes, seconds that counts down to the finish date. I have this:
function timer(){
'use strict'
var date1 = new Date().getTime();
var date2 = new Date("05/29/2017").getTime();
var diff = date2 - date1;
var seconds = diff / 1000;
var minutes = (diff / 1000) / 60;
var hours = minutes / 60;
var message = 'Hours: ' + Math.floor(hours) + " Minutes: " + Math.floor(minutes) + " Seconds: " + Math.floor(seconds);
var output = document.getElementById('output');
if (output.textContent !== undefined) {
output.textContent = message;
} else {
output.innerText = message;
}
}
setInterval("timer()", 1000);
window.onload = timer;
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hi</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="css/form.css">
</head>
<body>
<!-- auction.html -->
<form action="#" method="post" id="theForm">
<fieldset><legend>Auction ends on May 29, 2017</legend>
<p>Refresh page for updated times.</p>
<div id="output"></div>
<input type="submit" value="Refresh" id="submit">
</fieldset>
</form>
<script src="js/auction.js"></script>
</body>
</html>
The instructions for my assignment state that I need to: "Choose an end date in the future (several weeks after assignment is due) and use UTC. Display the hours, minutes, and seconds left until the auction ends."
I'm kind of lost on how to implement the UTC and create a proper countdown? I'm not even sure if I did any of it right (I am just starting to learn j.s). How should I fix my code?
In your code you have:
var date1 = new Date().getTime();
There's no need to use getTime in this case. But it is helpful to use meaningful variable names:
var now = new Date();
Then there's:
var date2 = new Date("05/29/2017").getTime();
Don't use the Date constructor (or Date.parse) to parse strings as it's mostly implementation dependent and inconsistent. If you have a specific date, pass values directly to the constructor.
Regarding "use UTC", that's a bit confusing as ECMAScript Date objects are UTC. They use the host timezone offset to calculate an internal UTC time value, and also to display "local" date and time values. The only way I can interpret "use UTC" is to use Date.UTC to create a date instance, e.g.:
var endDate = new Date(Date.UTC(2017,4,29)); // 2017-05-29T00:00:00Z
Now you can get the difference between then an now using:
var diff = endDate - now;
When trying to get the hours, minutes and seconds you have:
var seconds = diff / 1000;
var minutes = (diff / 1000) / 60;
var hours = minutes / 60;
That converts the entire difference to each of hours, minutes and seconds so the total time is about 3 times what it should be. What you need is just the components, so:
var hours = Math.floor(diff / 3.6e5);
var minutes = Math.floor(diff % 3.6e5) / 6e4);
var seconds = Math.floor(diff % 6e4) / 1000;
Putting it all together in one function:
function timeLeft() {
var now = new Date();
var endDate = new Date(Date.UTC(2017,4,29)); // 2017-05-29T00:00:00Z
var diff = endDate - now;
var hours = Math.floor(diff / 3.6e6);
var minutes = Math.floor((diff % 3.6e6) / 6e4);
var seconds = Math.floor((diff % 6e4) / 1000);
console.log('Time remaining to ' + endDate.toISOString() +
' or\n' + endDate.toString() + ' local is\n' +
hours + ' hours, ' + minutes + ' minutes and ' +
seconds + ' seconds');
}
timeLeft()
There are many, many questions and answers here about timers and date differences, do some searches.
You should really use momentjs for any datetime operation in javascript
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
// outputs: "00:39:30"

Having Trouble Creating A Timer To Count From a Given Time

I need for a clock to count from a specific time. e.g. Time is 20:08:00 and then to count from there. I have searched high and low for an answer and no one has specifically come up with an answer(that Ive seen). So my normal clock is like this.
<script type="text/javascript">
function clock()
{
var digital = new Date();
var hours = digital.getHours();
var minutes = digital.getMinutes();
var seconds = digital.getSeconds();
if (minutes <= 9) minutes = "0" + minutes;
if (seconds <= 9) seconds = "0" + seconds;
dispTime = hours + ":" + minutes + ":" + seconds;
var basicclock = document.getElementById('basicclock');
basicclock.innerHTML = dispTime;
setTimeout("clock()", 1000);
}
clock();
</script>
So all I need is the time to start at say 20:08:00 (or a variable of time). I am wondering if it better to use a timer to achieve a set time and to count from that???
Any help would be appreciated.
First: Please try to extensively search SO for answers before asking questions, many helpful responses can be found if you look. ;)
If you are trying to countdown to a certain time/date I would recommend the answer found HERE
All code credit goes to author's answer above.
HTML - for display
<span id="days"></span>
<span id="hours"></span>
<span id="minutes"></span>
<span id="seconds"></span>
Script (keep formatting and just modify the 4th line down for your target date)
setInterval(function(){
// set whatever future date / time you want here, together with
// your timezone setting...
var future = new Date("Sep 20 2014 21:15:00 GMT+0200");
var now = new Date();
var difference = Math.floor((future - now) / 1000);
var seconds = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var minutes = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var hours = fixIntegers(difference % 24);
difference = Math.floor(difference / 24);
var days = difference;
$("#seconds").text(seconds + "s");
$("#minutes").text(minutes + "m");
$("#hours").text(hours + "h");
$("#days").text(days + "d");
}, 1000);
function fixIntegers(integer)
{
if (integer < 0)
integer = 0;
if (integer < 10)
return "0" + integer;
return "" + integer;
}
DEMO OF THE ABOVE CODE
I would also look at these are other interesting solutions found on this post here HERE

Categories