JavaScript clock not displaying properly - javascript

I'm trying to make an updating JavaScript clock on my webpage. The problem I'm having is that, while the value itself updates (I use alert(timeNow) to show the value and make sure it's updating), the clock on the website doesn't. I was just wondering if there was something I was missing, or if I've just happened to come across something that I can't quite do. I'd prefer if there was a way to do it using jQuery, as I understand that a little better than normal JavaScript.
Javascript:
function updateClock() {
var thisDate = new Date();
if (thisDate.getHours() > 11 && thisDate.getHours() != 0) {
var Hours = Math.abs(thisDate.getHours() - 12);
var AmPm = "PM"
} else {
var Hours = thisDate.getHours()
var AmPm = "AM"
}
if (thisDate.getMinutes() < 10) {
var Mins = "0" + thisDate.getMinutes();
} else {
var Mins = thisDate.getMinutes();
};
var timeNow = thisDate.getDate() + "/" + (thisDate.getMonth() + 1) + "/" + thisDate.getFullYear() + " " + Hours + ":" + Mins + " " + AmPm;
return timeNow;
};
setInterval(updateClock, 1000);
$("span#time").append(updateClock());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="time"></span>

You are not consuming the return value of updateClock function, thus the updated time is not reflecting.
You should update the text of time span
Use
setInterval(function(){
$("span#time").text(updateClock());
}, 1000);

You are returning the time in the function updateClock(). What you actually want to do is to set it into the DOM at the end of updateClock(). Here is an updated example:
function updateClock() {
var thisDate = new Date();
if (thisDate.getHours() > 11 && thisDate.getHours() != 0) {
var Hours = Math.abs(thisDate.getHours() - 12);
var AmPm = "PM"
} else {
var Hours = thisDate.getHours()
var AmPm = "AM"
}
if (thisDate.getMinutes() < 10) {
var Mins = "0" + thisDate.getMinutes();
} else {
var Mins = thisDate.getMinutes();
};
var timeNow = thisDate.getDate() + "/" + (thisDate.getMonth()+1) + "/" + thisDate.getFullYear() + " " + Hours + ":" + Mins + " " + AmPm;
$("span#time").text(timeNow);
}
setInterval(updateClock, 1000);
You could of course also just use the returned value of updateClock() to update the DOM. In this way, you would separate the DOM manipulation and the JavaScript time calculation. #Satpal described this way.

Try This...
$(document).ready(function()
{
goforit();
});
var dayarray=new Array ("Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday")
var montharray=new Array("January","February","March","April","May","June",
"July","August","September","October","November","December")
function getthedate() {
d = new Date();
d.setUTCFullYear(2004);
d.setUTCMonth(1);
d.setUTCDate(29);
d.setUTCHours(2);
d.setUTCMinutes(45);
d.setUTCSeconds(26);
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var hours=mydate.getHours()
var minutes=mydate.getMinutes()
var seconds=mydate.getSeconds()
var dn=""
if (hours>=12)
dn=""
if (hours>12){
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds
//Hire change font size
var cdate=""
+ mydate.toLocaleString()
+""
if (document.all)
document.all.clock.innerHTML=cdate
else if (document.getElementById)
document.getElementById("clock").innerHTML=cdate
else
document.write(cdate)
}
if (!document.all&&!document.getElementById)
getthedate()
function goforit()
{
if (document.all||document.getElementById)
setInterval("getthedate()",1000)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<SPAN id=clock style="display:block"></SPAN>

setInterval(function() {
$("span#time").text(moment(new Date()).format('DD/M/YYYY LTS'));
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<span id="time"></span>

Related

solving the [object Object] issue

I'm trying to separate concerns using modules in Js eveything is going Ok except that I want to display the time of the system and I did that too but when I output it I got an [object Object] string and what proves me right that really I got the right system Time is that when I console logged the interCtrl.getTheTime I got the time of the system and here is a screenshot:
here is my code to let you understand better:
JS:
var controller = (function(interCtrl, UICtrl) {
//1.get the time
setInterval(document.querySelector(".Time").innerHTML = interCtrl.getTime(),100);
// console.log(interCtrl.getTime());
//2.get the date
document.querySelector(".subDate").innerHTML = interCtrl.date();
};
document.querySelector(".add__btn").addEventListener("click", ctrlAddPlans);
document.addEventListener("keypress", function(e) {
if (e.keyCode === 13) {
ctrlAddPlans();
}
});
})(internalController);
var internalController = (function() {
//some code
function getTheDate() {
var newDate;
var d = new Date();
var day = d.getDate();
var year = d.getFullYear();
var month = d.getMonth() + 1;
// var x=1;
if (month.toString().length < 2) {
month = " 0" + month + " ";
}
var date = " %11%/%04%/%2019%";
newDate = date.replace("%11%", day + " ");
newDate = newDate.replace("%04%", month);
newDate = newDate.replace("%2019%", " " + year);
return newDate;
}
function getTheTime() {
//.get the timeDiv
// const timeDiv =
//.get the time (h,m,s)
var date = new Date();
var hours = date.getHours();
if (hours.toString().length < 2) {
hours = `0${hours}`;
}
var mins = date.getMinutes();
if (mins.toString().length < 2) {
mins = `0${mins}`;
}
var seconds = date.getSeconds();
return {
time: hours+ " : "+ mins+" : "+seconds
};
}
return {
date: function getDate() {
return getTheDate();
},
getTime: function getTime() {
return getTheTime();
}
};
})();
I saw this question but it didn't help me what does [object Object] mean?
so any help please and thank you in advance
The output of the getTime function is an object. To make it output a string, you can change its return statement from
return {
time: hours+ " : "+ mins+" : "+seconds
};
to
return hours + " : " + mins+" : " + seconds;
Or, alternatively, if you want it to be an object, you'll have to access its time property to get the value. Like
var timeObj = interCtrl.getTheTime();
var timeString = timeObj.time;

Daily countdown timer - Display Message at 21:57

I'm struggling to figure out how Date() works, I found this on the web and wanted to make a countdown that stops at 21:57 UTC Time. It currently displays the message at 21:00 and apears until 22:00.
I tried to add if(currenthours != 21 && currentminutes >= 57){ and always broke it and got the message. I want it to stop 3 minutes before 22:00 and display the message. After it gets to 22:00 restart the countdown for the next day at 21:57.
Any help will be greatly appreciated !
var date;
var display = document.getElementById('time');
setInterval(function(){
date = new Date( );
var currenthours = date.getUTCHours();
// alert(currenthours);
var currentminutes = date.getUTCMinutes();
// alert(currentminutes);
var hours;
var minutes;
var secondes;
if (currenthours != 21) {
if (currenthours < 21) {
hours = 20 - currenthours;
} else {
hours = 21 + (24 - currenthours);
}
minutes = 60 - date.getUTCMinutes();
secondes = 60 - date.getUTCSeconds();
display.innerHTML = ('00' + hours).slice(-2) + ' HOURS ' + '<p>' +
('00' + minutes).slice(-2) + ' MINUTES ' + '</p>' +
('00' + secondes).slice(-2) + ' SECONDS';
} else {
display.innerHTML = "IT'S 21:57";
}
},1000);
<div id='time'></div>
Made a fiddle
https://jsfiddle.net/5qrs0tcp/1/
This is what I ended up with :
/*
|================================|
| COUNTDOWN TIMER |
|================================|
*/
// Return the UTC time component of a date in h:mm:ss.sss format
if (!Date.prototype.toISOTime) {
Date.prototype.toISOTime = function() {
return this.getUTCHours() + ':' +
('0' + this.getUTCMinutes()).slice(-2) + ':' +
('0' + this.getUTCSeconds()).slice(-2);
}
}
// Return the difference in time between two dates
// in h:mm:ss.sss format
if (!Date.prototype.timeDiff) {
Date.prototype.timeDiff = function(date2) {
var diff = Math.abs(this - date2);
return timeobj = {
hours : (diff/3.6e6|0), // hours
minutes : ('0' + ((diff%3.6e6)/6e4|0)).slice(-2), // minutes
seconds : ('0' + ((diff%6e4)/1e3|0)).slice(-2) // seconds
}
}
}
function countDown() {
var now = new Date();
var limitHr = 19;
var limitMin = 55;
var limitDate = new Date(+now);
// Set limitDate to next limit time
limitDate.setUTCHours(limitHr, limitMin, 0, 0);
// var msg = ['Currently: ' + now.toISOTime() + '<br>' + 'Limit: ' + limitDate.toISOTime()];
var msg = [];
var diff;
// If outside limitHr:limitMin to (limitHr + 1):00
if (now.getUTCHours() == limitHr && now.getUTCMinutes() >= limitMin) {
msg.push('Countdown stopped');
setTimeout(function(){
msg = ['Wait for it'];
var jsonCounter = {
stats : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
},5000);
var jsonCounter = {
stats : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
} else {
if (now > limitDate) limitDate.setDate(limitDate.getDate() + 1);
var jsonCounter = {
hours : now.timeDiff(limitDate).hours,
minutes : now.timeDiff(limitDate).minutes,
seconds : now.timeDiff(limitDate).seconds,
validating : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
}
}
setInterval(countDown, 1000);
var daily_status;
setTimeout( function(){
setInterval( function() {
jsonfile.readFile(DailyGamePath, (err, obj) => {
daily_status={
hours: obj.hours,
minutes: obj.minutes,
seconds: obj.seconds,
stats: obj.stats,
validating: obj.validating
};
return daily_status;
});
}, 1000);
}, 3000);
setTimeout( function(){
io.sockets.on('connection', (socket) => {
setInterval( function() {
// var GameStatus=DailyGameStatus();
socket.broadcast.emit('stream', {hours:daily_status.hours, minutes:daily_status.minutes, seconds:daily_status.seconds, stats:daily_status.stats, validating:daily_status.validating});
}, 1000);
});
}, 3000);
Date objects are very simple, they're just a time value and some handy methods.
I think your logic just needs to be:
if (currenthours != 21 && currentminutes < 57) {
// set the out of hours message
} else {
// time is from 21:57 to 21:59 inclusive
}
The countdown doesn't quite work because you're counting to 00 not to 57, but otherwise there doesn't seem to be an issue.
var date;
var display = document.getElementById('time');
setInterval(function(){
date = new Date( );
var currenthours = date.getUTCHours();
var currentminutes = date.getUTCMinutes();
var hours;
var minutes;
var secondes;
var limitHr = 5; // Change these to required values
var limitMin = 02; // Using 5:12 for convenience
var message = 'Currently: ' + date.toISOString() + '<p>';
// Create new message if outside limitHr:limitMin to limitHr:59 inclusive
if (currenthours != limitHr || currentminutes < limitMin) {
if (currenthours <= limitHr) {
hours = limitHr - currenthours;
} else {
hours = limitHr + (24 - currenthours);
}
minutes = limitMin - date.getUTCMinutes();
minutes += minutes < 0? 60 : 0;
secondes = 60 - date.getUTCSeconds();
message += ('00' + hours).slice(-2) + ' HOURS ' + '<p>' +
('00' + minutes).slice(-2) + ' MINUTES ' + '</p>' +
('00' + secondes).slice(-2) + ' SECONDS';
} else {
message += 'It\'s on or after ' + limitHr + ':' +
('0'+limitMin).slice(-2) + ' GMT';
}
// Display the message
display.innerHTML = message;
},1000);
<div id="time"></div>
Yes, the timer has issues but that wasn't part of the question. For a counter, it's simpler to just work in time differences, so I've added some methods to Date.prototype for ISO time (to be consistent with ISO Date) and time difference, then use those functions.
The function builds a Date for the end time so that calculations can use Date methods.
// Return the UTC time component of a date in h:mm:ss.sss format
if (!Date.prototype.toISOTime) {
Date.prototype.toISOTime = function() {
return this.getUTCHours() + ':' +
('0' + this.getUTCMinutes()).slice(-2) + ':' +
('0' + this.getUTCSeconds()).slice(-2) + '.' +
('00' + this.getUTCMilliseconds()).slice(-3) + 'Z';
}
}
// Return the difference in time between two dates
// in h:mm:ss.sss format
if (!Date.prototype.timeDiff) {
Date.prototype.timeDiff = function(date2) {
var diff = Math.abs(this - date2);
var sign = this > date2? '+' : '-';
return sign + (diff/3.6e6|0) + ':' + // hours
('0' + ((diff%3.6e6)/6e4|0)).slice(-2) + ':' + // minutes
('0' + ((diff%6e4)/1e3|0)).slice(-2) + '.' + // seconds
('00' + (diff%1e3)).slice(-3); // milliseconds
}
}
function countDown() {
var now = new Date();
var limitHr = 1;
var limitMin = 10;
var limitDate = new Date(+now);
// Set limitDate to next limit time
limitDate.setUTCHours(limitHr, limitMin, 0, 0);
var msg = ['Currently: ' + now.toISOTime() + '<br>' + 'Limit: ' + limitDate.toISOTime()];
var diff;
// If outside limitHr:limitMin to (limitHr + 1):00
if (now.getUTCHours() != limitHr || now.getUTCMinutes() != limitMin) {
if (now > limitDate) limitDate.setDate(limitDate.getDate() + 1);
msg.push(now.timeDiff(limitDate));
} else {
msg.push('It\'s after ' + limitHr + ':' + ('0'+limitMin).slice(-2));
}
document.getElementById('msgDiv2').innerHTML = msg.join('<br>');
}
window.onload = function() {
setInterval(countDown, 1000);
}
<div id="msgDiv2"></div>>
I've left the milliseconds in, round to seconds if you wish.
I've left the timer using setInterval, though I'd prefer to use setTimeout and manually calculate the time to just after the next full second so that it never skips. Most browsers using setTimeout will slowly drift so that they skip a second every now and then. Not really an issue unless you happen to see it, or compare it to the tick of the system clock.

is there possible to loop javascript function id?

is there possible to loop javascript function id? I have a form and the form is create using for loop; so I using this autosave javascript to save a draft; now the javascript only run the $("#remark1"). So I need to use for loop to loop the $("#remark1").
<script type="text/javascript">
$(function() {
if (localStorage) {
var content = localStorage.getItem("autoSave");
if(content) {
$("#remark1").text(content);
}
}
$("#remark1").autoSave(function() {
var time = showTime();
$("#msg").text("Draft Autosaved " + time).show();
}, 2000);
$("#refresh").click(function() {
location.reload();
});
$("#clear").click(function() {
localStorage.clear();
location.reload();
});
function showTime() {
var timeNow = new Date();
var hours = timeNow.getHours();
var minutes = timeNow.getMinutes();
var seconds = timeNow.getSeconds();
var timeString = "" + ((hours > 12) ? hours - 12 : hours);
timeString += ((minutes < 10) ? ":0" : ":") + minutes;
timeString += ((seconds < 10) ? ":0" : ":") + seconds;
timeString += (hours >= 12) ? " P.M." : " A.M.";
return timeString;
}
});
I want to loop ("remark1"), any kind solution?
Do you mean something like this?
function dynamicSave( id ) {
$("#" + id).autoSave(function() {
var time = showTime();
$("#msg").text("Draft Autosaved " + time).show();
}, 2000);
}
var ids = [ 'remark1', 'remark2' ];
ids.each(function(id) {
dynamicSave( id );
});

Jquery How to check today time greater then use given time?

How to check time conditionin Jquery
var startTime="20:02:55"; // or 12:34
var endTime ="21:02:55" // or 1:34
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
if(time >startTime || time < endTiime){
$("#a").html("show Box");
}else{
$("#a").html("Expire BOx");
}
How to check 12 hour and 24 hour condition also?
is it correct? i need am, pm format check please can anyone help me?
Here is some code. I am appending to show both behaviour.
Here is DEMO
test("20:02:55", "21:02:55");
test("13:02:55", "15:02:55");
function test(start_time, end_time) {
var dt = new Date();
//convert both time into timestamp
var stt = new Date((dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear() + " " + start_time);
stt = stt.getTime();
var endt = new Date((dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear() + " " + end_time);
endt = endt.getTime();
var time = dt.getTime();
if (time > stt && time < endt) {
$("#a").append("<br> show Box ");
} else {
$("#a").append("<br> Expire BOx ");
}
}
Try this.
I took the logic to print 'Show Box' if the current time is in between the start and end time. else viceversa.
var startTime="20:02:55"; // or 12:34
var endTime ="21:02:55" // or 1:34
var dt = new Date();
var st = new Date('00','00','00',startTime.split(':')[0],startTime.split(':')[1],startTime.split(':')[2]);
var et = new Date('00','00','00',endTime.split(':')[0],endTime.split(':')[1],endTime.split(':')[2]);
if(dt.getTime() >st.getTime() && dt.getTime() < et.getTime()){
alert("show Box");
}else{
alert("Expire BOx");
}

Subtract to function times

I currently have two functions that capture the current dates minute in which a user loads and leaves a page.
Is there a way to combine these functions so that I can get the difference?
Ex. User loads the page at 30, and leaves at 45
Therefore, 45-30 = 15 minutes
Also is there any reason why my unload alert does not work on safari?
JAVASCRIPT
<script type="text/javascript">
window.onload = function () {
var currentdate = new Date();
var hour = currentdate.getHours();
var minutes = currentdate.getMinutes();
var seconds = currentdate.getSeconds();
alert("starts at " + minutes + " minutes");
}
window.onbeforeunload = function (e) {
var currentdate = new Date();
var hour = currentdate.getHours();
var minutes = currentdate.getMinutes();
var seconds = currentdate.getSeconds();
return ("leaves at " + minutes + " minutes");
}
</script>
Something like this ?
var pageLoadTime;
window.addEventListener("load", function () {
pageLoadTime = (new Date()).getTime();
});
window.addEventListener("beforeunload", function (e) {
var pageUnloadTime = (new Date()).getTime();
var secondsPassed = Math.round((pageUnloadTime - pageLoadTime) / 1000);
var hoursPassed = Math.floor(secondsPassed / 3600);
secondsPassed = secondsPassed % 3600;
var minutesPassed = Math.floor(secondsPassed / 60);
secondsPassed = secondsPassed % 60;
alert(hoursPassed + " hour(s), " + minutesPassed + " minute(s), " + secondsPassed + " second(s)");
});

Categories

Resources