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.
Related
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();
My clock script is as follows. For some reason if(minutes<10){minutes="0"+minutes;} and if(seconds<10){seconds="0"+seconds;} will add a 0 before a number less than 10, but it won't do it for the hours. Any advice on how to fix it?
<script>
function TimeUpdate() {
var now = new Date(), hours = now.getHours(), minutes = now.getMinutes(), seconds = now.getSeconds();
// The 1st "if" does not work.
if (hours < 10) {hours = "0" + hours;}
if (minutes < 10) {minutes = "0" + minutes;}
if (seconds < 10) {seconds = "0" + seconds;}
// (This works) AM or PM option
if (hours >= 12 && hours < 24) {var TimeOfDay = "PM";}
else {var TimeOfDay = "AM";}
// (This works) Converts the hours from 24 to 12
if (hours > 12) {hours = hours - 12;}
// This sets the hours to a specific number.
// This is used only for this demonstration.
hours = 5;
// (This works) Puts everything together
var CurrentTime = hours + ':' + minutes + ':' + seconds + " " + TimeOfDay;
// (This works) The clock <div>
var MyClock = document.getElementById('clock');
// (This works) Writes the "CurrentTime" to the clock's <div>
MyClock.innerHTML = CurrentTime;
var t = setInterval (function () {TimeUpdate ()}, 1000);
}
// (This works) This loads the clock onto the page.
window.onload = TimeUpdate;
</script>
<p id="clock"></p>
You're overwriting your check. Move that block of code further down:
function TimeUpdate() {
var now = new Date(),
hours = now.getHours(),
minutes = now.getMinutes(),
seconds = now.getSeconds();
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
// (This works) AM or PM option
if (hours >= 12 && hours < 24) {
var TimeOfDay = "PM";
} else {
var TimeOfDay = "AM";
}
// (This works) Converts the hours from 24 to 12
if (hours > 12) {
hours = hours - 12;
}
// This sets the hours to a specific number.
// This is used only for this demonstration.
hours = 5;
// The 1st "if" does not work.
if (hours < 10) {
hours = "0" + hours;
}
// (This works) Puts everything together
var CurrentTime = hours + ':' + minutes + ':' + seconds + " " + TimeOfDay;
// (This works) The clock <div>
var MyClock = document.getElementById('clock');
// (This works) Writes the "CurrentTime" to the clock's <div>
MyClock.innerHTML = CurrentTime;
var t = setInterval(function() {
TimeUpdate()
}, 1000);
}
// (This works) This loads the clock onto the page.
window.onload = TimeUpdate;
<br>
<br>
<br>
<p id="clock"></p>
You need to place
if (hours < 10) {
hours = "0" + hours;
}
after
if (hours > 12) {
hours = hours - 12;
}
since it has to be true for hours of 13-21 (1-9 PM) as well.
Watch out for that code. That's a recursive function, you'll blow your computer memory in no time. Please remove the TimeUpdate() from inside itself
function TimeUpdate() {
var now = new Date(),
hours = now.getHours(),
minutes = now.getMinutes(),
seconds = now.getSeconds();
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
// (This works) AM or PM option
if (hours >= 12 && hours < 24) {
var TimeOfDay = "PM";
} else {
var TimeOfDay = "AM";
}
// (This works) Converts the hours from 24 to 12
if (hours > 12) {
hours = hours - 12;
}
// This sets the hours to a specific number.
// This is used only for this demonstration.
hours = 5;
// The 1st "if" does not work.
if (hours < 10) {
hours = "0" + hours;
}
// (This works) Puts everything together
var CurrentTime = hours + ':' + minutes + ':' + seconds + " " + TimeOfDay;
// (This works) The clock <div>
var MyClock = document.getElementById('clock');
// (This works) Writes the "CurrentTime" to the clock's <div>
MyClock.innerHTML = CurrentTime;
}
// (This works) This loads the clock onto the page.
var t = setInterval(function() {
TimeUpdate()
}, 1000);
<br>
<br>
<br>
<p id="clock"></p>
I have a javascript code set into my webpage but the date time is always two hours off. If anyone knows what's wrong please help.
Here's my relevant JavaScript code:
function show() {
var Digital = new Date()
var hours = Digital.getHours()
var minutes = Digital.getMinutes()
var seconds = Digital.getSeconds()
var dn = "AM"
if (hours > 12) {
dn = "PM"
hours = hours - 12
}
if (hours == 0) c
hours = 12
if (minutes <= 9)
minutes = "0" + minutes
if (seconds <= 9)
seconds = "0" + seconds
document.dform.currenttime.value = hours + ":" + minutes + ":" + seconds + " " + dn
setTimeout("show()", 1000)
}
show();
You have a c right here:
if (hours==0)c
Delete the c. It works. You're welcome.
I suggest proofreading your code before you come asking for help, but more importantly you should format your code so that it's legible enough to proofread. As an example:
function show() {
var Digital = new Date();
var hours = Digital.getHours();
var minutes = Digital.getMinutes();
var seconds = Digital.getSeconds();
var dn = "AM";
if(hours > 12) {
dn = "PM";
hours -= 12;
}
if(hours == 0) hours = 12;
if(minutes <= 9) minutes = "0" + minutes;
if(seconds <= 9) seconds = "0" + seconds;
document.dform.currenttime.value = hours + ":" + minutes + ":" + seconds + " " + dn;
}
var clock = setInterval(show, 1000);
This is easier to read and you likely would've noticed the erroneous c.
What I'm trying to do is for example if the local time is 6:00PM I would like to display the time 10 minutes ahead which would be 6:10PM and for the other time I would like to go 50 minutes back from the current time so that would be 5:10PM.. what I have so far does neither since I can only figure out how to display the current time
<script>
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
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>")
</script>
How do I go back 50 minutes and ahead 10 minutes?
This should suffice
<script>
var futureTime = new Date();
futureTime.setMinutes(futureTime.getMinutes()+10);
var pastTime = new Date();
pastTime.setMinutes(pastTime.getMinutes()-50);
</script>
Then just use the pastTime and futureTime variables with your existing display code.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
function formatDate(d)
{
var hours = d.getHours();
var minutes = d.getMinutes();
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
if (hours == 0)
{
hours = 12;
}
if (minutes < 10)
{
minutes = "0" + minutes;
}
return hours + ":" + minutes + " " + suffix;
}
var currentTime = new Date();
var futureTime = new Date(currentTime.getTime());
futureTime.setMinutes(futureTime.getMinutes() + 10);
var pastTime = new Date(currentTime.getTime());
pastTime.setMinutes(pastTime.getMinutes() - 50);
document.write("<b>" + formatDate(currentTime) + "</b>");
document.write("<b>" + formatDate(futureTime) + "</b>");
document.write("<b>" + formatDate(pastTime) + "</b>");
I am using following code to display date on my webpage. I need to update it every minute. How to do that?
var d=new Date();
var n=d.toString();
document.write(n);
Currently its static, means when the page load, datetime of that moment is displayed. I have to update time every minutes without refreshing the page.
Try with setInterval(): http://jsfiddle.net/4vQ8C/
var nIntervId; //<----make a global var in you want to stop the timer
//-----with clearInterval(nIntervId);
function updateTime() {
nIntervId = setInterval(flashTime, 1000*60); //<---prints the time
} //----after every minute
function flashTime() {
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
var time = h + ' : ' + m + ' : ' + s;
$('#my_box1').html(time); //<----updates the time in the $('#my_box1') [needs jQuery]
}
$(function() {
updateTime();
});
You can use document.getElementById("my_box1").innerHTML=time; instead of $('#my_box1')
from MDN:
About setInterval : --->Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
About setTimeout : ----> Calls a function or executes a code snippet after specified delay.
Here is how you can print date time every second
function displayDate()
{
var n=BuildDateString();
document.write(n);
window.setTimeout("displayDate();", 1000); // to print it every minute take 1000*60
}
function BuildDateString()
{
var today = new Date()
var year = today.getYear()
if (year < 2000)
year = "19" + year
var _day = today.getDate()
if (_day < 10)
_day = "0" + _day
var _month = today.getMonth() + 1
if (_month < 10)
_month = "0" + _month
var hours = today.getHours()
var minutes = today.getMinutes()
var seconds = today.getSeconds()
var dn = "AM"
if (hours > 12)
{
dn = "PM"
hours = hours - 12
}
if (hours == 0)
hours = 12
if (minutes < 10)
minutes = "0" + minutes
if (seconds < 10)
seconds = "0" + seconds
var DateString = _month+"/"+_day+"/"+year+" "+hours+":"+minutes+":"+seconds+" "+dn
return DateString;
}
I am using following approach:
var myVar=setInterval(function(){myDateTimer()},60000);
function makeArray()
{
for (i = 0; i<makeArray.arguments.length; i++)
this[i + 1] = makeArray.arguments[i];
}
function myDateTimer()
{
var months = new makeArray('January','February','March','April','May',
'June','July','August','September','October','November','December');
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
var hours = date.getHours();
var minutes = date.getMinutes();
var finaldate = days[ date.getDay() ] + ", " + months[month] + " " + day + ", " + year + " " + hours +" : " + minutes;
document.getElementById("showDateTime").innerHTML=finaldate;
}
just do this
$(function(){
setInterval(function(){
var d=new Date();
var n=d.toString();
$('#test').html(n);
},1000);
});
demo http://runjs.cn/code/txlexzuc