Trying to get it to change between 16:30:00 and 17:30:00, to change the text font colour
Tried nested if statements as well
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
if ((h>=16 && m >=30) && (h<=17 && m<=30))
{
document.getElementById("txt").style.color = "red";
}
else
{
document.getElementById("txt").style.color = "black";
}
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
try to use setInterval() it's look more clear:
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
if((h==16 && m>=30) || (h==17 && m<=30)){
document.getElementById("txt").style.color = "red";
}
else
{
document.getElementById("txt").style.color = "black";
}
};
setInterval(startTime, 500);
The main bug in your logic is looking for minutes where it is both less than and equal to 30 AND greater than and equal to 30. The only way that part evaluates to true is if minutes is 30.
I would normalize the time (so that each combination of hour, minute and second can be represented by a unique number) and use that for comparisons.
function startTime(el) {
var today = new Date();
var hour = today.getHours(),
minute = today.getMinutes(),
second = today.getSeconds();
var normalized_time = normalizeTime(hour, minute, second);
document.getElementById(el).innerHTML
= hour + ":" + padTime(minute) + ":" + padTime(second);
document.getElementById(el).style.color
= normalized_time >= normalizeTime(16, 30, 0)
&& normalized_time <= normalizeTime(17, 30, 0)
? 'red'
: 'black';
}
/*
* Add a 0 to the beginning of the number if one-digit number
*/
function padTime(i) {
return i < 10 ? '0' + i : i;
}
/*
* Converts the time to a normalized version
*/
function normalizeTime(h, m, s) {
return s + (60 * m) + (60 * 60 * h);
}
var t = setInterval(startTime, 500, 'txt');
<span id="txt"></span>
Edit: As per you question you want to take hour and minute into account for comparison, So i have not included the second's part.
The following function get an integer value against time , that later used for the comparison.
function getSeconds(hh,mm,ss)
{
return (Number(hh) * 60 * 60) + (Number(mm) * 60) + Number(ss);
}
Complete code :
function getSeconds(hh,mm,ss)
{
return (Number(hh) * 60 * 60) + (Number(mm) * 60) + Number(ss);
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
var timeNow = getSeconds(h,m,s);
//if ((h>=16 && m >=30) && (h<=17 && m<=30))
if (timeNow >= getSeconds(16,30,0) && timeNow <= getSeconds(17,30,00))
{
document.getElementById("txt").style.color = "red";
}
else
{
document.getElementById("txt").style.color = "black";
}
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
startTime();
Updated Fiddle
Previous Response
Try the Fiddle
The problem with your code is you are comparing m with contradictory conditions.
I have concatenated the hour and minutes like following and used that for time comparison
var hrs = Number(h+'.'+m);
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
var hrs = Number(h+'.'+m);
//if ((h>=16 && m >=30) && (h<=17 && m<=30))
if (hrs >= 16.30 && hrs <= 17.30)
{
document.getElementById("txt").style.color = "red";
}
else
{
document.getElementById("txt").style.color = "black";
}
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
startTime();
Related
This question already has answers here:
Fire event at a certain time of the day
(4 answers)
Closed 11 months ago.
im a noob in js xd, i want to put a text in an html in a choosen time of a clock!
i want it to print "make a wish" when its 11:11
the code:
function startTime() {
const today = new Date();
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
setTimeout(startTime, 1000);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
This can be done via setInterval in javascript with some basic if condition checks.
First create a date object via new Date() then get hours and minutes, check if the hour and minute is equal to your specified time then print the value.
We need to set an interval of 60 seconds which is equal to 60,000 milliseconds to not print again the same value in that minute.
You can try this -
setInterval(function(){
var date = new Date();
if(date.getHours() === 11 && date.getMinutes() === 11){
console.log("make a wish");
}
}, 60000);
Something like this will do.
function startTime() {
const today = new Date();
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
if (h == 11 && m == 11) {
console.log("Make a wish");
} else {
setTimeout(startTime, 1000);
}
}
function checkTime(i) {
if (i < 10) { i = "0" + i }; // add zero in front of numbers < 10
return i;
}
startTime();
<p id="txt"></p>
Use the callback function from SetInterval and get currentt time. afterwards you can check if it 11:11. If successful dont forget to clear the intervall.
const innterval = setInterval(function () {
check()
}, 5000);
function check() {
var today = new Date();
var t1111 = today.getHours() + ':' + today.getMinutes();
if (t1111 === '11:11') {
alert('11:11')
document.getElementById('txt').innerHTML = t111 + ' PARTY!'
clearInterval(innterval);
}
console.log('Current time: ' + t1111 + ' still Waiting')
}
<div id="txt"></div>
I've been given some JavaScript that creates a digital clock to go onto a webpage. This is working perfectly, however, I'm trying to amend it to wrap the am/pm suffix (or Diem in this code) in span or bold tags so that I can style it differently to the rest of the time in the CSS.
I'm sure this would be really simple for someone that knows what they're doing but I'm really struggling.
Any help would be appreciated, the JavaScript is below:
function renderTime() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
setTimeout('renderTime()',1000);
if (h == 0) {
h = 12;
} else if (h > 12) {
h = h - 12;
diem="PM";
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('clockDisplay');
myClock.textContent = h + ":" + m + " " + diem;
myClock.innerText = h + ":" + m + " " + diem;
var diem = document.createElement('span');
}
renderTime();
So, I want to do the same thing, but in a URL style, like this: http://example.com/example?h="10"&m="42"
Just concatenate the hour and minute to the URL prefix and return that as a string.
Also, your code produces the wrong diem for times between noon and 12:59, since those should be 12PM.
function getTimeURL() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
if (h == 0) {
h = 12;
} else if (h > 12) {
h = h - 12;
diem="PM";
} else {
diem = "PM";
}
if (m < 10) {
m = "0" + m;
}
var url = `http://example.com/example?h=${h}${diem}&m=${m}`;
return url;
}
console.log(getTimeURL());
I added a bunch of comments to your code that'll hopefully make it easier to understand. I also added a global variable that will store your linkText value as it's changed by the function.
// create a global variable that stores our text for the link.
// Your renderTime() function will update it every second.
var linkText = "";
function renderTime() {
//grab the new date
var currentTime = new Date();
//set diem (whatever that means) to "AM"
var diem = "AM";
//get the hours from our current time
var h = currentTime.getHours();
//get the minutes
var m = currentTime.getMinutes();
//get the seconds
var s = currentTime.getSeconds();
//run this function every 1000 milliseconds
setTimeout('renderTime()', 1000);
//if the hour is 0, set it to twelve instead
if (h == 0) {
h = 12;
//else if the hour is any number higher than 12,
//subtract 12 from its value and change diem to "PM"
} else if (h > 12) {
h = h - 12;
diem = "PM";
}
//if the minutes are 0-9 add a 0 before.
if (m < 10) {
m = "0" + m;
}
//if the seconds are 0-9 add a 0 before.
if (s < 10) {
s = "0" + s;
}
//get our clock element
var myClock = document.getElementById('clockDisplay');
//populate our clock element
myClock.textContent = h + ":" + m + ":" + s + " " + diem;
myClock.innerText = h + ":" + m + ":" + s + " " + diem;
//not sure why you're writing over your AM/PM variable at the end here,
//so I commented it out
//var diem = document.createElement('span');
//set our linkText value to be the current hour and minute
linkText = 'http://example.com/example?h="' + h + '"&m="' + m + '"';
}
//run that thang!
renderTime();
<div id="clockDisplay"></div>
This is how the JavaScript looks like. I tried searching for solutions but couldn't find. Please I need detailed solutions. Online I kept seeing cookies but I don't know how to use it in this case.
function countDown() {
var now = new Date();
var eventDate = new Date(2020, 5, 22);
var currentTime = now.getTime();
var eventTime = eventDate.getTime();
var remTime = eventTime - currentTime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s/60);
var h = Math.floor(m/60);
var d = Math.floor(h/24);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h: h;
m = (m < 10) ? "0" + m: m;
s = (s < 10) ? "0" + s: s;
document.getElementById("days").textContent = d;
document.getElementById("days").innerText = d;
document.getElementById("hours").textContent = h;
document.getElementById("minutes").textContent = m;
document.getElementById("seconds").textContent = s;
var t = setTimeout(countDown, 1000);
if (d == 0 && h == 0 && m == 0 && s == 0) {
clearTimeout(t);
document.getElementById("demo").innerHTML = "Happy Birthday!"
}
}
countDown();
</script>
The trouble with your code is in the date checking logic.
Checking with == will only give you a truthy response if the datetime (or part thereof) is the same as the value you're checking it against.
However, you need to check whether the date is already past. To do this, you need to use a < or <= operator.
Here's an example of what I mean. The info is console.loged instead, you can re-implement the DOM editing you have in your question.
function countDown() {
var now = new Date();
var eventDate = new Date(2020, 4, 22); // 22 May 2020
var currentTime = now.getTime();
var eventTime = eventDate.getTime();
var remTime = eventTime - currentTime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s/60);
var h = Math.floor(m/60);
var d = Math.floor(h/24);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h: h;
m = (m < 10) ? "0" + m: m;
s = (s < 10) ? "0" + s: s;
var t = setTimeout(countDown, 1000);
// This if statement only runs exactly on eventDate
if (d == 0 && h == 0 && m == 0 && s == 0) {
document.getElementById("demo").innerHTML = "Happy Birthday!"
}
// This if statement will run if we're past or exactly on eventDate
if (remTime <= 0) {
clearTimeout(t);
}
// This console.log shows that the numbers become negative after the date
console.log(remTime, d,h,m,s);
}
countDown();
I am trying to get a div element to update once one minute goes by from.
I have a function in Javascript that counts down to a specific time in the day, however, I would like to use JQuery so that as the timer is counting down when the minute changes instead of having to refresh the browser it does it without refreshing.
I had a timer that displayed hours, minutes, seconds counting down to a specific setHours() using a setTimout to countdown.
function countdown() {
var now = new Date();
var eventDate = new Date();
var currentTiime = now.getTime();
var eventTime = eventDate.setHours(16, 30, 0);
var remTime = eventTime - currentTiime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
var h = Math.floor(m / 60);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
document.getElementById("hours").textContent = h;
document.getElementById("minutes").textContent = m;
document.getElementById("seconds").textContent = s;
if (now.getHours() >= 9 && currentTiime < eventTime) {
setTimeout(countdown, 1000);
}
At the moment I have a countdown that countdown to 16:30 but displays as:
Hours: minutes: seconds: I would like Hours:xx minutes:xx and when the minute goes down 1 minute it shows in the div without refreshing the page.
Here is a solution that has a bit of JQuery strewn in. Please note that your Javascript solution will work as well. The only difference is that this calls setInterval instead of setTimeout ('setInterval' vs 'setTimeout')
Please try running the code snippet here or on JSFiddle: https://jsfiddle.net/raghav710/tbvmj4px/ . This updates the value without refreshing the page.
EDIT: Added condition to handle when the current time is greater than event time
function get_elapsed_time_string(total_seconds) {
var now = new Date();
var eventDate = new Date();
var currentTime = now.getTime();
var eventTime = eventDate.setHours(17, 00, 0);
var remTime = eventTime - currentTime;
if(remTime <= 0){
clearInterval(interval_id);
$("#hours").html(0);
$("#minutes").html(0);
$("#seconds").html(0);
}
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
var h = Math.floor(m / 60);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
$("#hours").html(h);
$("#minutes").html(m);
$("#seconds").html(s);
}
var elapsed_seconds = 0;
var interval_id =
setInterval(function() {
elapsed_seconds = elapsed_seconds + 1;
get_elapsed_time_string(elapsed_seconds);
console.log(interval_id);
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="hours"></div>
<div id="minutes"></div>
<div id="seconds"></div>
function countdown(){
var now = new Date();
var eventDate = new Date();
var currentTiime = now.getTime();
var eventTime = eventDate.setHours(16, 30, 0);
var remTime = eventTime - currentTiime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
var h = Math.floor(m / 60);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? h +" hrs" : h + "hrs";
h = (h <= 1) ? "" : h;
m = (m < 10) ? "0" + m + " mins" : m + " mins ";
if(now.getHours() >= 9 && currentTiime < eventTime){
setTimeout(countdown, 1000);
document.getElementById("timer").textContent = h + " " + m;
}
else if(now.getHours() < 9 || currentTiime >= eventTime){
var t = document.getElementsByClassName("order-day")[0];
t.getElementsByClassName("order-day")[0].textContent = "Order by 4:30pm for same day dispatch";
hideCountdown();
}
I have a Rails app where I'm displaying a realtime clock in my application layout. I'm using this code to make it work:
<div id="time" class="time_display"></div>
<script type="text/javascript">
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();
</script>
What I'd like to be able to do is somehow give the user the option to switch between a realtime clock in military time and regular AM/PM time with the AM/PM included but clicking on the div.
I've done some searching but haven't found anything that works too well. I'm open to any solutions someone might have be it JS or jQuery.
Any help would be greatly appreciated. If my question is not clear, please let me know.
Here is code. It get updated only on next tick, but you can manage to fix that if you want
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();
var ampm = h >= 12 ? 'pm' : 'am';
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
var timer = document.getElementById('time');
if (timer.type == 'r') {
h = h % 12;
h = h ? h : 12;
timer.innerHTML = h + ":" + m + ":" + s + " " + ampm;
} else
timer.innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
document.getElementById('time').onclick = function () {
if (this.type == 'r')
this.type = 'm';
else
this.type = 'r';
}
}
startTime();
<div id="time" class="time_display"></div>
Really:
var ampm = 'am';
if(hours > 11){
ampm = 'pm';
if(hours > 12)hours = hours-12;
}
if(hours === 0)hours = 12;
Also, you could do something like:
today.toLocaleString().split(',')[1];