JavaScript Clock Not displaying Correctly - javascript

I'm having an issue where I have a digital sign and it accepts embedded HTML. I created a widget for it to display a clock, I tried downloading one and they never worked for some reason so made my own. The issue that I am having is that the clock does not display the correct time. I got it so the numbers display correctly but the issue that I am seeing now is that it will dsiplay AM instead of PM. I would appreciate any help, not sure if the logic is right or if I used the wrong condition statements. Any help would be awesome, Thanks!
<script type="text/javascript">
function updateTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var p;
if (minutes < 10){
minutes = "0" + minutes;
}
if (seconds < 10){
seconds = "0" + seconds;
}
if (hours >= 12){
p = "PM"; //could not get this in it's own if statement w/o breaking it
hours = (hours - 12);
}
if (hours == 0) {
hours = (hours + 12);
}else {
p = "AM";
}
var v = hours + ":" + minutes + ":" + seconds + " " + p;
setTimeout("updateTime()", 1000);
document.getElementById('time').innerHTML= v;
}
updateTime();
</script>
<style type="text/css">
#time {
font-size: 5em;
}
</style>
<div><span id="time"></span></div>

change your IFs to:
if (hours >= 12) {
p = "PM";
hours = (hours>12) ? (hours - 12) : 12;
}
else
{
if (hours == 0)
hours = 12;
p = "AM";
}

Your code was almost right, there is just one little mistake you're making. when you check if hours is greater than 12, p is PM else p should be AM. You can solve this by setting p to AM at the beginning of the function, of moving the else you already have up right after the check.
This Fiddle will demonstrate a working example: http://jsfiddle.net/s2R9y/
if (hours >= 12) {
p = "PM";
hours = (hours - 12);
} else {
p = "AM";
}
The setTimeOut function has been fixed aswell, so it actually worked:
setTimeout(updateTime, 1000);

Related

What is the purpose of this line of code if (hours == 00) { hours = 12; } please explain to me

I want to know in this code what is the meaning of the line of code asked in the question why this code is used. Can you tell me what the meaning of this line is? I wonder what the use of this line is.
$(document).ready(function () {
function showTime() {
// To Get the current time/date
var date = new Date();
//Make Variables to get hours, minute, and second
var hours = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
// AM, PM Setting
var session = "AM";
// Conditions for time behavior
if (hours == 00) {
hours = 12;
}
if (hours >= 12) {
session = "PM";
}
if (hours > 12) {
hours = hours - 12;
}
hours = hours < 10 ? "0" + hours : hours;
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
// Set the variable to span
$("#hours").text(hours);
$("#min").text(min);
$("#sec").text(sec);
$("#period").text(session);
// To change time in every seconds
setTimeout(showTime, 1000);
}
showTime();
});
If the hour is 00, meaning 12 in the morning (midnight), it changes the string value to show '12' instead of '00', in order to display the time in 12-hour format.

How to get a "0" before "1" to "9" in a clock

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>

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.

Javascript date time two hours off

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.

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