Countdown.js tweaking - javascript

I'm using countdown.js: http://blog.smalldo.gs/2013/12/create-simple-countdown/
I have no experience with JavaScript, and I need the countdown to be set to a week from now, 7 days, so February 24, 2014.
How would I go about changing this?
Here is what I have in my html:
<head>
<script src="/js/countdown.js"></script>
</head>
<h1 id="countdown-holder"></h1>
<script>
var clock = document.getElementById("countdown-holder")
, targetDate = new Date(2050, 00, 01); // Jan 1, 2050;
clock.innerHTML = countdown(targetDate).toString();
setInterval(function(){
clock.innerHTML = countdown(targetDate).toString();
}, 1000);
</script>

Just change targetDate = new Date(2050, 00, 01);
to targetDate = new Date(2014, 01, 24);
The date constructor takes year, month-1, day.
This is for a fixed date (such as Feb 24 2014), not a relative date (such as "one week from today").

var newDate = new Date();
var numberOfDaysToAdd = 7;
newDate.setDate(newDate.getDate() + numberOfDaysToAdd);
var clock = document.getElementById("countdown-holder")
, targetDate = newDate;
clock.innerHTML = countdown(targetDate).toString();
setInterval(function(){
clock.innerHTML = countdown(targetDate).toString();
}, 1000);
This will start counter from 7 days. It will add 7 days to todays date.

try something like this, here is also the js fiddle:
http://jsfiddle.net/rnewsome/D3tPR/
Requires an html element on the page like so:
<div id="counter" />
var StartTime = new Date();
var counter = document.getElementById("counter");
var timeout = null;
function GetCount() {
var timeToExpire = new Date(StartTime);
timeToExpire.setDate(timeToExpire.getDate() + 7);
var ms = timeToExpire.getTime() - new Date().getTime();
console.log(ms + "ms", (ms/1000) + "s");
return ms;
};
function UpdateUI() {
var timeRemaining = parseInt(GetCount() / 1000);
counter.innerHTML = timeRemaining + " seconds";
if(timeRemaining > 0) {
timeout = setTimeout(UpdateUI , 1000); // Update Counter every second
}
}
// Init
UpdateUI();

Related

Call a Javascript function every second with setInterval

I try to get the function for my JavaScript countdown running every second but somehow I don't get the setInterval function to work.
This is how the JS code looks so far:
// Set end date and time
var enddate = new Date();
endTimeDate = "2022-01-12 21:52";
// Get date and time of today
var today = new Date();
// Calculate date and time difference
function getTimeDifference(endtime) {
var total = Date.parse(endtime) - Date.parse(today);
var seconds = Math.floor((total/1000) % 60);
var minutes = Math.floor((total/1000/60) % 60);
var hours = Math.floor((total/1000/60/60) % 24);
var days = Math.floor(total/1000/60/60/24);
return {
total,
days,
hours,
minutes,
seconds
};
}
function runCountdown() {
var t = getTimeDifference(endTimeDate);
document.getElementById('days').innerHTML = t.days + " D";
document.getElementById('hours').innerHTML = t.hours + " H";
document.getElementById('minutes').innerHTML = t.minutes + " M";
document.getElementById('seconds').innerHTML = t.seconds + " S";
}
window.setInterval(runCountdown, 1000);
The reason your code is not working as expected because you're declaring today outside of the function which means it's called only once , hence the diff result will always be the same. You probably want to move the assignment and the declaration of var today = new Date(); inside the getTimeDifference function so there will be an actual difference between the enddate value and the today value.
// Set end date and time
var enddate = new Date();
endTimeDate = "2022-01-12 21:52";
// Get date and time of today
// Calculate date and time difference
function getTimeDifference(endtime) {
var today = new Date();
console.log(endtime);
var total = Date.parse(endtime) - Date.parse(today);
var seconds = Math.floor((total/1000) % 60);
var minutes = Math.floor((total/1000/60) % 60);
var hours = Math.floor((total/1000/60/60) % 24);
var days = Math.floor(total/1000/60/60/24);
return {
total,
days,
hours,
minutes,
seconds
};
}
function runCountdown() {
var t = getTimeDifference(endTimeDate);
document.getElementById('days').innerHTML = t.days + " D";
document.getElementById('hours').innerHTML = t.hours + " H";
document.getElementById('minutes').innerHTML = t.minutes + " M";
document.getElementById('seconds').innerHTML = t.seconds + " S";
}
window.setInterval(runCountdown, 1000);
<div id="days">
</div>
<div id="hours">
</div>
<div id="minutes">
</div>
<div id="seconds">
</div>

How to update current day at midnight or basically on new day in Javascript

So I have web watch what should work 24/7. It displaying digital time and current day. Nothing else.
My problem is that when time past midnight, current day won't update and I need to restart whole application.
I tried to add setTimeout for showDate() function, but it didn't help me. I was thinking about moving +1 on array of days. Is there anything more effective?
function showdate(){
var date = new Date();
var day = date.getDay();
var name = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][day];
document.getElementById("date").textContent = name;
}
showdate();
function showTime(){
var date = new Date();
var h = date.getHours(); // 0 - 23
var m = date.getMinutes(); // 0 - 59
var s = date.getSeconds(); // 0 - 59
var session = "AM";
if(h === 0){
h = 24;
}
/*if(h > 12){
h = h - 12;
session = "PM";
}*/
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s;
/*var sess = session;*/
document.getElementById("MyClockDisplay").innerText = time;
document.getElementById("MyClockDisplay").textContent = time;
/* document.getElementById("PM").textContent = sess;*/
setTimeout(showTime, 1000);
}
showTime();
Thank you for any idea.
Your code doesn't execute itself automatically. You shall call it periodically like this :
function showdate(){
var date = new Date();
var day = date.getDay();
var name = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][day];
document.getElementById("date").textContent = name;
console.log('show date');
}
setInterval(showdate, 1000)
This way, the client will get the new date every second (where 1000 is in milliseconds). But you can change the time to any value (keep in mind it's in ms) that fit your needs.
You also can take a look at this example.
function showdate(){
var date = new Date();
var day = date.getDay();
var name = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][day];
document.getElementById("date").textContent = name;
console.log('show date');
}
setInterval(showdate, 1000)
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function() {
startTime()
}, 500);
}
startTime();
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="date"></div>
<div id="time"></div>
</body>
</html>
You can do:
// Show date every day at 12
function showdateEveryDayAt12() {
setInterval(function() {
showdate();
}, 86400000);
}
// Show date at next 12, and call showdateEveryDayAt12()
function showdateAtNext12() {
var now = new Date();
var millisecondsTo12 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 0, 0, 0) - now;
setTimeout(function() {
showdate();
showdateEveryDayAt12();
}, millisecondsTo12);
}
// Show date
function showdate() {
var date = new Date();
var day = date.getDay();
var name = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][day];
document.getElementById("date").textContent = name;
}
// Show date now, at next 12 and every day at 12
showdate();
showdateAtNext12();
<p id="date"></p>

problem with changes GMT( time zone )?

I created a small script to display the time(UTC-+3.5). The problem is there that changes GMT(+4.5, +3.5) in Iran every six months in year, and changes Time is pulled back and forth (Daylight Saving)
How i set yourself clock with change GMT in iran? what do i do? (now GMT in iran is +4.5)
EXAMPLE: my code-jsfiddle
var int = self.setInterval("clock()", 1000);
function clock() {
var d = calcTime('+4.5')
var t = d.toLocaleTimeString();
document.getElementById("clock").innerHTML = t;
}
function calcTime(offset) {
d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000 * offset));
return nd;
}
With respect
Fiddle Example
<script type="text/javascript">
var int = self.setInterval("clock()", 1000);
function clock() {
var d = calcTime('+4.5')
var t = d.toLocaleTimeString();
document.getElementById("clock").innerHTML = t;
}
function calcTime(offset) {
d = new Date();
ds = new Date(); // new Daylight Savings Time object
ds.setMonth(9); // Set month to september
ds.setDate(21); // set day to 21st
if(d > ds){ // if current date is past the daylight savings date minus one from the offset
offset = eval(offset - 1);
}
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000 * offset));
return nd;
}
</script>
<b id="clock"></b>
This works. It will check if the date is currently past September 21st and if it is it will -4.5 from GMT otherwise 3.5
it is not the cleanest code i've ever written, I just modified yours. however you can see how it is done now.

How do you get the unix timestamp for the start of today in javascript?

I realize that the current timestamp can be generated with the following...
var timestamp = Math.round((new Date()).getTime() / 1000);
What I'd like is the timestamp at the beginning of the current day. For example the current timestamp is roughly 1314297250, what I'd like to be able to generate is 1314230400 which is the beginning of today August 25th 2011.
Thanks for your help.
var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay / 1000;
Well, the cleanest and fastest way to do this is with:
long timestamp = 1314297250;
long beginOfDay = timestamp - (timestamp % 86400);
where 86400 is the number of seconds in one day
var now = new Date; // now
now.setHours(0); // set hours to 0
now.setMinutes(0); // set minutes to 0
now.setSeconds(0); // set seconds to 0
var startOfDay = Math.floor(now / 1000); // divide by 1000, truncate milliseconds
var d = new Date();
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
var t = d / 1000;
Alternatively you could subtract the modulo of a days length in miliseconds e.g.
var day = 24*60*60*1000;
var start_of_today = Date.now() - Date.now() % day;
Luis Fontes' solution returns UTC time so it can be 1 hour (daylight saving time) different from setHours solution.
var d = new Date();
var t = d - (d % 86400000);
Simplified version of examples above (local time).
var d = new Date();
d.setHours(0,0,0,0);
var t = d / 1000;
Here you can find some performance tests: http://jsperf.com/calc-start-of-day
Another alternative for getting the beginning of the day is the following:
var now = new Date();
var beginningOfDay = new Date(now.getTime() -
now.getHours() * 60 * 60 * 1000 -
now.getMinutes() * 60 * 1000 -
now.getSeconds() * 1000 -
now.getMilliseconds());
var yoursystemday = new Date(new Date().getTime()-(120000*60+new Date().getTimezoneOffset()*60000));
yoursystemday = new Date();
var current_time_stamp = Math.round(yoursystemday.getTime()/1000);
For any date it's easy to get Timestamps of start/end of the date using ISO String of the date ('yyyy-mm-dd'):
var dateString = '2017-07-13';
var startDateTS = new Date(`${dateString}T00:00:00.000Z`).valueOf();
var endDateTS = new Date(`${dateString}T23:59:59.999Z`).valueOf();
To get ISO String of today you would use (new Date()).toISOString().substring(0, 10)
So to get TS for today:
var dateString = (new Date()).toISOString().substring(0, 10);
var startDateTS = new Date(`${dateString}T00:00:00.000Z`).valueOf();
var endDateTS = new Date(`${dateString}T23:59:59.999Z`).valueOf();
var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay.getTime() / 1000;

Call a javascript function at a specific time of day

for example i want to call a js function at 10.00.00.00 am
how can i do?
<script type="text/javascript">
var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 30, 0, 0) - now;
setTimeout(function{openAPage(), setInterval(openAPage, 60*1000)}, millisTill10)
function openAPage() {
var startTime = new Date().getTime();
var myWin = window.open("http://google.com","_blank")
var endTime = new Date().getTime();
var timeTaken = endTime-startTime;
document.write("<br>button pressed#</br>")
document.write(new Date(startTime));
document.write("<br>page loaded#</br>")
document.write(new Date(endTime));
document.write("<br>time taken</br>")
document.write(timeTaken);
myWin.close()
}
</script>
i expect from this code at 00.30 it will open google and then every 1 minute later it will do it again? whats wrong with that code?
You'll need setTimeout to set a timer and Date to calculate how long the timer needs to go until it triggers.
var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
millisTill10 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function(){alert("It's 10am!")}, millisTill10);
My solution for running a script at a specific time, btw no error checking for negative timeout.
//year, month 0-11, date, hour, min (can add ,sec,msec)
var eta_ms = new Date(2015, 0, 21, 17, 0).getTime() - Date.now();
var timeout = setTimeout(function(){}, eta_ms);
Assuming the code is located on a web page that will be loaded before 10:00 and will still be viewed at 10:00, you can use setTimeout() to set up a timed event. the function takes some JS statement to execute, and the number of milliseconds before it should execute. You can find this second part pretty easily with the built-in date functions.
Try this
$(document).ready(function() {
setTimeToTrigger();
});
function setTimeToTrigger(){
var dt = new Date();
var hour = dt.getHours();
var minute = dt.getMinutes() ;
var seconds = dt.getSeconds();
if(hour<10){
nexthour=9;
}else if(hour<22){
nexthour=21;
}else{
nexthour=23-hour+9;
}
delaytime=(nexthour-hour)*60*60+(59-minute)*60+(59-seconds);
alert('will be triggered in :'+ delaytime + ' seconds');
setTimeout( function() {
alert("The time is 10:00");
}, delaytime*1000);
}
<html>
<head>
<title>alert at specific time</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h3>Alert at at 10:00 AM and 10:PM</h3>
</body>
</html>

Categories