Javascript daily countdown - javascript

I want to have a continuous daily countdown where the plan will have 2 schedule/specific time daily.
I am now still troubleshoot at 1 specific time.
The following is modification from this answer https://stackoverflow.com/a/23512971/20903104
<script type="text/javascript">
function executeAction (target){
console.log(target);
//next schedule
};
var date;
var remaining = document.getElementById("remaining");
var schedule1 = document.getElementById("schedule1").value.split(":");
var target = schedule1[0];
setInterval(function () {
date = new Date();
var currenthours = date.getHours();
var hours;
var minutes;
var secondes;
if (currenthours != target) {
if (currenthours < target) hours = target - 1 - currenthours;
else hours = target + (24 - currenthours);
minutes = 60 - date.getMinutes();
secondes = 60 - date.getSeconds();
remaining.innerHTML = hours + ":" + minutes + ":" + secondes;
} else {
remaining.innerHTML = "LIVE NOW";
executeAction(target);
//continue to next schedule
};
}, 1000);
</script>
Let say, now is 11:00 (AM) the next schedule is 10:00 (AM) the output is:
enter image description here
it should be 23:00:00 and counting down
I want to add second (or third schedule) and add this code :
<input type="time" id="schedule1" value="10:00:00" readonly />
<div id="remaining"></div>
<input type="time" id="schedule2" value="22:00:00" readonly />
<div id="remaining2"></div>
How to proceed to next schedule continuously?
complete code : https://jsfiddle.net/kuraba/6or71L90/14/

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();

Moment.js format difference

In one of my projects i have to calculate the difference between two times. For example the work hours starts at 6:30 and finishes at 10 o'clock. The difference is 3 hours and 30 minutes. I write a small JS function to handles the task and it works great, gives me the following result: 3.5.
I tried .format("HH:mm") but the result was undefined not a function.
Is there any method that converts the output like "HH:mm"?
Here is the dateDiff function:
function dateDiff() {
var startTime = moment(document.getElementById("startTime").value, "HH:mm");
var endTime = moment(document.getElementById("end").value, "HH:mm");
var duration = moment.duration(endTime.diff(startTime));
var hours = duration.asHours();
console.log(hours);
document.getElementById('dateDiffResult').value = moment(hours);
}
You could just get the hours and minutes separately and format the string:
function dateDiff() {
var startTime = moment(document.getElementById("startTime").value, "HH:mm");
var endTime = moment(document.getElementById("end").value, "HH:mm");
var duration = moment.duration(endTime.diff(startTime));
var hours = duration.hours();
var minutes = duration.minutes();
document.getElementById('dateDiffResult').value = hours +":"+ minutes;
}
if your function works and gives you the time difference in hours, surely it is then simple to calculate the hours and minutes from the number of hours? Using your stated difference of 3.5...
var diff=3.5;
var hour=Math.floor(diff);//gives hour=3;
var hours=("0"+ hour).slice(-2);//pads the hours with a leading zero if required to give hours=03;
var minute = (diff-hour)*60;//gives 30
var minutes=("0"+ minute ).slice(-2);//pads the minutes with a leading zero if required to give minutes=30;
var totalDiff= hours + ":" +minutes; //gives 03:30 as in HH:MM
I added the following to demonstrate this in the snippet:
$(document).ready
(function(){
var diff=3.5;
var hour=Math.floor(diff);//gives hour=3;
var hours=("0"+ hour).slice(-2);//gives hours=03;
var minute = (diff-hour)*60;//gives 30
var minutes=("0"+ minute ).slice(-2);//gives minutes=30;
var totalDiff= hours + ":" +minutes; //gives 03:30 as in HH:MM
alert("HH:MM: " + totalDiff);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Using a time-field jQuery plugin, you can generate time fields. After that, you can listen to changes to the fields and update the hours difference accordingly.
(function($) {
$.initTimeFields = function(interval) {
$('.time-field').each(function(_, field) {
$(field).initTimeField(interval);
});
};
$.fn.initTimeField = function(interval) {
var hour = 0, minute = 0, diff;
while (hour < 24 && minute < 60) {
this.append($('<option>', {
val : hour * 60 + minute,
text : ('00' + hour).substr(-2) + ':' + ('00' + minute).substr(-2)
}));
minute += interval;
diff = minute - 60;
if (diff >= 0) {
hour += 1;
minute %= 60;
}
}
var value = this.data('value') || 0;
if (typeof value === 'string' && value.indexOf(':') > -1) {
value = (function(values) {
return parseInt(values[0], 10) * 60 + parseInt(values[1], 10);
}(value.split(':')));
}
this.val(value);
};
}(jQuery));
function updateTimeDiff() {
$('#hour-diff').val(calcHourDiff(getTime('#start-time'), getTime('#end-time')) + ' hours');
}
function calcHourDiff(startTime, endTime) {
var diff = moment.duration(endTime.diff(startTime));
return ('00' + diff.hours()).substr(-2) + ':' + ('00' + diff.minutes()).substr(-2);
}
function getTime(selector) {
return moment($(selector).find('option:selected').text(), "HH:mm");
}
$('.time-field').on('change', function() {
updateTimeDiff()
});
// Main
$.initTimeFields(15);
$('.time-field').trigger('change');
label { display: inline-block; width: 3em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<label>Start: </label><select id="start-time" class="time-field" data-value="06:30"></select><br />
<label>End: </label><select id="end-time" class="time-field" data-value="10:00"></select><br />
<label>Diff: </label><input id="hour-diff" type="text" size="8" />

How to get End time based on selected Start time and Interval?

Currently working on a project where I have to build time picker with start, end time and interval of meeting. User first pick start time for example 7:15am, then next step is to pick meeting interval that range from 5 min up to 60 min, and last step is end time that should start based on picked start time and meeting interval. So if user pick 7:30am for start time, and pick meeting interval 50 min, my end time should start at 8:20am, 9:10am, 10:00am,... all the way up to 5pm but not greater than. First problem with my current is Start Time picker, in drop down next to 12 hour value I should have PM. My code gives me AM. Second is End Time works fine if I pick meeting interval from 5 min up to 45 min, but if I pick meeting length 50 min or 55 min I'm not getting correct end time values in drop down.
HTML:
<tr>
<th>Start Time:</th>
<td>
<select name="stime" id="stime" />
<option value="">--Select start time--</option>
</select>
</td>
<br />
<th>Meeting Length:</th>
<td>
<select name="meet_leng" id="meet_leng" onClick="setEndTime()">
<option value="">--Select length--</option>
</select>
</td>
<br />
<th>End Time:</th>
<td>
<select name="etime" id="etime"/>
<option value="">--Select end time--</option>
</select>
</td>
</tr>
JavaScript:
$(function() {
for(var i=5; i <= 60; i+=5){
$('#meet_leng').append('<option value="'+i+'">'+i+' min'+'</option>');
}
for(var i=700; i<= 1700; i+=15){
var mins = i % 100;
var hours = parseInt(i/100);
if (mins > 45) {
mins = 0;
hours += 1;
i = hours * 100;
}
var standardTime = ' AM';
if(hours > 12){
standardTime = ' PM';
hours %= 13;
hours++;
}else{
hours %= 13;
}
$('#stime').append('<option value="'+i+'">'+('0' + (hours)).slice(-2)+':'+('0' +mins).slice(-2)+standardTime+'</option>');
}
});
function setEndTime(){
var meetingLength = $('#meet_leng').val();
var selectedTime = $('#stime').val();
var sum = meetingLength + selectedTime;
for(var i=sum; i <= 1700; i+=meetingLength){
var mins = i % 100;
var hours = parseInt(i/100);
if (mins > 59) {
var new_mins = mins % 60;
hours += 1;
i = (hours * 100) + new_mins;
}
$('#etime').append('<option value="'+i+'">'+i+'</option>');
}
}
Here is my working example: https://jsfiddle.net/dmilos89/rhuh6qum/22/.
If anyone can help with this problem please let me know.
basically you could look at using the Date api instead. In the bottom example, we have a startTime which can be a string,
we split it into integers
create a new Date object and set the time to the startTime
add your change in minutes
then pull out the new hour/minutes and format as you please
(i think there are ways to get this via the Date api, but i figured heavy handed was fine for the example)
https://jsfiddle.net/2fpg3rte/1/
var time = new Date();
var startTime = "12:01 PM";
var timeChange = 60; //60 minutes
var startHour = startTime.split(':')[0];
var startMin = startTime.split(':')[1].replace(/AM|PM/gi, '');
time.setHours(parseInt(startHour));
time.setMinutes(parseInt(startMin));
$("#start").html(getFormattedTime(time));
//adjusted time
time.setMinutes(time.getMinutes() + timeChange);
$("#end").html(getFormattedTime(time));
function getFormattedTime(time) {
var postfix = "AM";
var hour = time.getHours();
var min = time.getMinutes();
//format hours
if (hour > 12) {
hour = (hour - 12 === 0) ? 12 : hour - 12;
postfix = hour === 0 ? "AM" : "PM";
}
//format minutes
min = (''+min).length > 1 ? min : '0' + min;
return hour + ':' + min + ' ' + postfix;
}

How to get Javascript clock to increment based on a button click

I have the following piece of JavaScript which currently displays a digital clock on my webpage. I am creating a web based interactive story which is based on a day in the office. Everytime the user clicks a button to proceed onto the next part of the story I want to increment the clock by 30 minutes. Currently the clock is just showing real time. Ideally it would need to start at 9:00 am for the story then increment as the user goes through.
I have absolutely no idea how to do this and am fairly new to JavaScript, hopefully someone can help!
function displayTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var meridiem = "am"; // Default is AM
if (hours > 12) {
hours = hours - 12; // Convert to 12-hour format
meridiem = "PM"; // Keep track of the meridiem
}
if (hours === 0) {
hours = 12;
}
if(hours < 10) {
hours = "0" + hours;
}
if(minutes < 10) {
minutes = "0" + minutes;
}
if(seconds < 10) {
seconds = "0" + seconds;
}
var clockDiv = document.getElementById('clock');
clockDiv.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
}
displayTime();
setInterval(displayTime, 1000); });
To start at 09:00 o'clock, you could use
var d = new Date();
d.setHours(9);
d.setMinutes(0);
d.setSeconds(0);
Then, I would recommend using moment.js
function onClick() {
d = moment(d).add(30, "minutes").toDate();
var el = document.getElementById('clock');
el.innerHTML = moment(d).format("HH:mm:ss");
}
You can also do it without moment.js
function pad(t) {
return t < 10 ? "0" + t : t;
}
function onClick() {
d.setMinutes(d.getMinutes() + 30);
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var time = pad(h) + ":" + pad(m) + ":" + pad(s);
document.getElementById("clock").innerHTML = time;
}
JSFiddle Demo (moment.js)
JSFiddle Demo (vanilla)
Working code (jquery), but you need to modify it according to your needs,
function displayTime(currentTime, hours, minutes, seconds) {
var meridiem = "am"; // Default is AM
if (hours > 12) {
hours = hours - 12; // Convert to 12-hour format
meridiem = "PM"; // Keep track of the meridiem
}
if (hours === 0) {
hours = 12;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
$('#clock').text(hours + ":" + minutes + ":" + seconds + " " + meridiem);
}
$(function() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
displayTime(currentTime, hours, minutes, seconds);
$('#increment30').on('click', function() {
currentTime.setMinutes(currentTime.getMinutes() + 30);
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
displayTime(currentTime, hours, minutes, seconds);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id='clock'>sss</div>
<button id='increment30'>INCREMENT 30</button>
Hi here is another one try here http://jsfiddle.net/Ltq9dhaw/ :
var time = new Date();
time.setHours(9);
time.setMinutes(0);
time.setSeconds(0);
function displayTime() {
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
var meridiem = "am"; // Default is AM
if (hours > 12) {
hours = hours - 12; // Convert to 12-hour format
meridiem = "PM"; // Keep track of the meridiem
}
if (hours === 0) {
hours = 12;
}
if(hours < 10) {
hours = "0" + hours;
}
if(minutes < 10) {
minutes = "0" + minutes;
}
if(seconds < 10) {
seconds = "0" + seconds;
}
var clockDiv = document.getElementById('clock');
clockDiv.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
}
document.querySelector('#add').addEventListener('click',function(){
var minutes = 30;
time = new Date(time.getTime() + minutes*60000);
displayTime();
});
displayTime();
I'm gonna throw my hat in the ring here too.
var date = new Date(); // create a new Date object
date.setHours(9); // set it to 09:00:00
date.setMinutes(0);
date.setSeconds(0);
setInterval(function(){ // loop...
date.setSeconds(date.getSeconds()+1); // increment the seconds by 1
var str = ''; // build up a formatted string from the Date object
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
str += h.toString().length==1 ? '0' : ''; // if we have a single digit, prepend with a '0'
str += h;
str += ':'
str += m.toString().length==1 ? '0' : ''; // and again
str += m;
str += ':'
str += s.toString().length==1 ? '0' : ''; // and again
str += s;
$('#time').html(str); // set the element with ID 'time' to contain the string we just built
}, 1000); // ... every second
$('#increment').click(function(){ // when i click the element with id 'increment'
date.setMinutes(date.getMinutes()+30); // add 30 minutes to our Date object
});
Note that you will need to include jQuery on your page.
You can do that with the following snippet:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
Since you are using jQuery you can keep it simple:
function fmt2(v){return v<10?'0'+v:''+v;}
$(function(){
var t=new Date();t.setHours(9);t.setMinutes(0);t.setSeconds(0);
var offset=t.getTime() - new Date().getTime();
function displayTime(){
var currentTime= new Date((new Date()).getTime()+offset);
var hours = currentTime.getHours();
var meridiem=hours>=12?"PM":"AM";
hours=hours%12;
if (hours==0) hours=12;
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
$('#clock').text( fmt2(hours)+':'
+fmt2(minutes)+':'
+fmt2(seconds)+' '+meridiem);
}
$('#newtime').click(function(){offset+=60*30*1000;});
setInterval(displayTime,1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clock">09:00:00 AM</div>
<a id="newtime" href=#>add time</a>
I am working basically with the real time but there is an offset applied to it. The offset is calculated such, that the clock will always start at 9:00 AM.

How Do I Create A Countdown Time That Resets At A Specific Time

Let me first say I do not have a deep understanding of javascript but I know how to work my way around enough to write small scripts for pages. A client of mine needs me to do the following for a website:
Find the user's local time on their computer.
Take that local time and subtract it from 6pm.
Display that time in a countdown or just a statement letting the user know how much time is left for same day shipping.
After 6pm the time resets or disappears until the next business day.
So far I've been able to create the logic for getting the time from the local computer. I thought I'd be able to use datejs but it does not calculate hours in a day.
Here is the current code I have:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
if (hours == 0)
{
hours = 12;
}
if (minutes < 10)
minutes = "0" + minutes;
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>");
How about this:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (minutes < 10)
minutes = "0" + minutes
if (suffix == "PM" && hours >= 6)
{
document.write("You're too late for next day shipping!");
}
else
{
var hoursLeft = 5 - hours;
var minsLeft = 60 - minutes;
document.write("<b> You've got " + hoursLeft + " hours and " + minsLeft + " minutes left to qualify for next day shipping! </b>")
}
if this site would let me comment on other people's answers I'd give the credit for this to Giovanni, but since I can't yet comment on other people's work, here's what needs to change.
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (minutes < 10)
minutes = "0" + minutes
if (hours >= 18)
{
document.write("You're too late for next day shipping!");
}
else
{
var hoursLeft = 17 - hours;
var minsLeft = 60 - minutes;
if(minsLeft==60){
minsLeft=0;
hoursLeft++;
}
document.write("<b> You've got " + hoursLeft + " and " + minsLeft + " minutes left to qualify for next day shipping! </b>")
}
The reason for this is that people who are ordering at 5AM might see think that they have to submit within the next hour for their shipping to be next day when in fact they have the next 13 hours.
EDIT: saw your timezone concern and here is a post that might interest you.
EDIT 2: posted the wrong link. The correct one should be up now, though it might be a bit of a dated answer.
Something similar I solved also yesterday, so this is easy. Here is the javascript code:
function start_onload(last_hour){
var timeout_message = document.getElementById('timeout_message');
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var expire_time = 0; // in seconds
if (hours<last_hour) {
expire_time += (last_hour-hours-1)*3600;
expire_time += (59-minutes)*60;
expire_time += (59-seconds);
}
else {
timeout_message.innerHTML = 'It\'s after '+last_hour+' o\'clock!';
return;
}
var expire_time = currentTime.getTime() + 1000*expire_time;
//console.log(expire_time, hours, minutes, seconds, expire_time);
function countdown_session_timeout() {
var current_time = new Date().getTime();
var remaining = Math.floor((expire_time - current_time)/1000);
if (remaining>0) {
hours = Math.floor(remaining/3600);
minutes = Math.floor((remaining - hours*3600)/60);
seconds = remaining%60;
timeout_message.innerHTML = 'Countdown will stop in '+ hours + ' hours ' + minutes + ' min. ' + seconds + ' sec.';
setTimeout(countdown_session_timeout, 1000);
} else {
timeout_message.innerHTML = 'Time is up!';
}
}
countdown_session_timeout();
}
Full script # pastebin.com is here.
This is a simple countdown timer starting at 30 seconds from when the function is run and ending at 0. After reaching 0 it automatically reset the counter. It goes again to 30 second and this process is continued in a loop
window.onload = function() { startCountDown(30,
1000, myFunction); }
function startCountDown(i, p, f) { var pause = p; var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
//write out count
countDownObj.innerHTML = i;
if (i == 0) {
//execute function
//fn();
startCountDown(30, 1000, myFunction); //stop
return; } setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
); } //set it going countDownObj.count(i); }
function myFunction(){};
</script>

Categories