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];
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>
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();
This question already has answers here:
How do you display JavaScript datetime in 12 hour AM/PM format?
(31 answers)
Closed 8 years ago.
Currently shows the time in a 24 Hour clock format. Can this be chnaged to show a 12 Hour clock with AM or PM? Thanks
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(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
Yes, if you want to continue formatting manually, you can use something like this:
element.innerHTML = (h > 12 ? h - 12 : h) + ":" + m + ":" + s + (h >= 12 ? " PM" : " AM");
new Date().toLocaleTimeString()
/* returned value: (String)
eg. 11:25:50 AM
or 8:08:41 PM
*/
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
var ampm = h >= 12 ? 'pm' : 'am';
h = h % 12;
h = h ? h : 12;
m = m < 10 ? '0' + m : m;
var strTime = h + ':' + m + ':' + s +' ' + ampm;
document.getElementById('txt').innerHTML = strTime;
var t = setTimeout(function () { startTime() }, 500);
}
function checkTime(i) {
if (i < 10) { i = "0" + i }; // add zero in front of numbers < 10
return i;
}
DEMO
Im creating a JS clock/date. I previously got the time to work perfectly then I decided to add more onto my clock (date). Right now I cant figure why it isn't working. If anyone could give me tip or idea how to fix it, I would greatly appreciate it.
function timedate()
{
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var dn="PM"
var d = currentTime.getDate(); <--
var day = (d < 10) ? '0' + d : d;
var m = currentTime.getMonth() + 1; <--
var month = (m < 10) ? '0' + m : m;
var yy = currentTime.getYear(); <--
var year = (yy < 1000) ? yy + 1900 : yy;
if (hours<12)
{
dn="AM"
}
if (hours>12)
{
hours=hours-12
}
if (hours==0)
{
hours=12
}
if (minutes<=9)
{
minutes="0"+minutes
}
var clocklocation = document.getElementById('timedate');
clocklocation.innerHTML = "" +hours+":"+minutes+dn+""+day + "/" + month + "/" + year;
setTimeout("timedate()", 1000);
}
timedate();
Your code works, it is just not visible because you do not have seconds showing
Also change
setTimeout("timedate()", 1000);
to
setTimeout(timedate, 1000);
because it is not recommended
and remove the <--
Make sure it runs onload or after the tag you want to show it in
Alternatively remove the line and change
timedate();
to
setInterval(timedate,1000)
const pad = num => ("0" + num).slice(-2);
const timedate = () => {
const currentTime = new Date();
let hours = currentTime.getHours();
const minutes = pad(currentTime.getMinutes());
const seconds = pad(currentTime.getSeconds());
const d = currentTime.getDate();
const day = pad(d);
const month = pad(currentTime.getMonth() + 1);
const yy = currentTime.getFullYear();
let dn = "PM"
if (hours <= 12) dn = "AM";
if (hours >= 12) hours -= 12;
if (hours == 0) hours = 12;
hours = pad(hours);
document.getElementById('timedate').innerHTML = "" +
hours + ":" +
minutes + ":" +
seconds + dn + " " +
day + "/" + month + "/" + yy;
}
window.addEventListener("load", function() {
setInterval(timedate, 1000);
});
<span id="timedate"></span>
If you set the timeout with setTimeout(timedate, 1000) instead of your current magic string version, it works1.
1 I took the liberty of adding seconds to your code as well, to make it obvious that the clock updates. Of course, you also need to remove <-- from your code.