I need more than one clock. In my attempt, I replaced document.getElementById with Document.getElementsByClassName. Unfortunately, it does not work the way I tried. Can someone help me please?
function currentTime() {
var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();
var midday = "AM";
midday = (hour >= 12) ? "PM" : "AM";
hour = (hour == 0) ? 12 : ((hour > 12) ? (hour - 12): hour);
hour = updateTime(hour);
min = updateTime(min);
let hours = document.createElement('span')
let points = document.createElement('span')
let mins = document.createElement('span')
let blank = document.createElement('span')
let middays = document.createElement('span')
hours.innerHTML = hour
points.innerHTML = ":"
mins.innerHTML = min
blank.innerHTML = " "
middays.innerHTML = midday
document.getElementById("clock").innerHTML = ""
document.getElementById("clock").appendChild(hours);
document.getElementById("clock").appendChild(points);
document.getElementById("clock").appendChild(mins);
document.getElementById("clock").appendChild(blank);
document.getElementById("clock").appendChild(middays);
var t = setTimeout(currentTime, 1000);
}
function updateTime(k) {
if (k < 10) {
return "0" + k;
}
else {
return k;
}
}
currentTime();
<p id="clock"></p>
const clocks = document.querySelectorAll('.clock');
function currentTime() {
var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();
var midday = "AM";
midday = (hour >= 12) ? "PM" : "AM";
hour = (hour == 0) ? 12 : ((hour > 12) ? (hour - 12): hour);
hour = updateTime(hour);
min = updateTime(min);
const clock = `${hour}:${min} ${midday}`
for (var i = 0; i < clocks.length; i++) {
clocks[i].innerHTML = clock;
}
var t = setTimeout(currentTime, 1000);
}
function updateTime(k) {
if (k < 10) {
return "0" + k;
}
else {
return k;
}
}
currentTime();
<p class="clock"></p>
<p class="clock"></p>
<p class="clock"></p>
Using getElementsByClassName(), if you read the function, elements is plural. The function getElementsByClassName() actually returns an array! So, you just need to use:
document.getElementsByClassName('class')[index].
Hopefully, you understand how arrays work. If not, here is MDN and w3schools. I recommend reading w3schools first then seeing MDN
you can't have multiple id on the same page, so you need to replace that with a class and select all of them with document.querySelectorAll(".class-name") you can then loop over it.
I done this, expect it was about your question ?
function currentTime(elementsClass)
{
let AllClock = document.getElementsByClassName(elementsClass)
, theClock = AllClock[0]
, hours = document.createElement('span')
, points = document.createElement('span')
, mins = document.createElement('span')
, blank = document.createElement('span')
, middays = document.createElement('span')
, date = null
, hour = null
, theClockInnerHTML = ''
;
theClock.appendChild(hours);
theClock.appendChild(points);
theClock.appendChild(mins);
theClock.appendChild(blank);
theClock.appendChild(middays);
points.textContent = ":"
blank.textContent = " "
updateClock()
setInterval(updateClock, 1000);
function updateClock()
{
date = new Date()
hour = date.getHours()
hours.textContent = time2digits( (hour == 0) ? 12 : ((hour > 12) ? (hour - 12): hour) )
mins.textContent = time2digits( date.getMinutes())
middays.textContent = (hour >= 12) ? "PM" : "AM"
if (theClock.innerHTML!=theClockInnerHTML) {
theClockInnerHTML = theClock.innerHTML
for(let i=1;i<AllClock.length;i++) {
AllClock[i].innerHTML = theClockInnerHTML
}
}
}
function time2digits(k)
{
return (k < 10) ? ("0" + k) : k
}
}
currentTime('clock');
<p class="clock"></p>
<p class="clock"></p>
<p class="clock"></p>
Related
Example i have shift like so:
Shift Schedule
Shift 1: 5:00 AM - 1:00 PM
Shift 2: 1:00 PM - 9:00 PM
Shift 3: 9:00 PM - 5:00 AM
These shift details are read from a textbox that are populated with PHP / sql query
some location may only have 1 or 2 shifts so if NA NA there is no shift and closed
Seems about 00:15~~ give or take we jump back to shift 2 for about 45 minutes then at around 01:00 back to correct shift number.. I have messed with this code multiple time through the program development and I am close to the final and this is a remaining bug i'm not super pro at java and had used some helper code from some fiddles to mutt this together!
Any insight would be great and thank you in advance!
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
setInterval(showShift, 1000);
function showShift() {
var myshift = 0;
var time = new Date($("#DATETIME").val());
if ($("#shift1start").val() == 'NA NA' && $("#shift1end").val() == 'NA NA') {var status = "CLOSED"}
else {
var timeh1 = time.getHours();
var timem1 = time.getMinutes();
const Start1Time = convertTime12To24($("#shift1start").val());
var s1 = Start1Time.split(':');
const End1Time = convertTime12To24($("#shift1end").val());
var e1 = End1Time.split(':');
var start_time1 = [parseInt(s1[0], 10),0]
var end_time1 = [parseInt(e1[0], 10),0]
var now1 = [timeh1,timem1]
if(end_time1[0] < start_time1[0] && now1[0] < start_time1[0]){
start_time1[0] -= 24;
}else if(start_time1[0] > end_time1[0]){
end_time1[0]+=24;
}
var start_string1 = to_hms_string(start_time1); //the start string converted to a string format. Made comparisons easier.
var end_string1 = to_hms_string(end_time1); //See Above
var now_string1 = to_hms_string(now1); //Above
console.log(start_string1, now_string1, end_string1);
var status = (start_string1 < now_string1 && now_string1 < end_string1) ? "1" : "0";
if (status == 1) {myshift = 1;}
}
if ($("#shift2start").val() == 'NA NA' && $("#shift2end").val() == 'NA NA') {var status = "CLOSED"}
else {
var timeh2 = time.getHours();
var timem2 = time.getMinutes();
const Start2Time = convertTime12To24($("#shift2start").val());
var s2 = Start2Time.split(':');
const End2Time = convertTime12To24($("#shift2end").val());
var e2 = End2Time.split(':');
var start_time2 = [parseInt(s2[0], 10),0]
var end_time2 = [parseInt(e2[0], 10),0]
var now2 = [timeh2,timem2]
if(end_time2[0] < start_time2[0] && now2[0] < start_time2[0]){
start_time2[0] -= 24;
}else if(start_time2[0] > end_time2[0]){
end_time2[0]+=24;
}
var start_string2 = to_hms_string(start_time2); //the start string converted to a string format. Made comparisons easier.
var end_string2 = to_hms_string(end_time2); //See Above
var now_string2 = to_hms_string(now2); //Above
console.log(start_string2, now_string2, end_string2);
var status = (start_string2 < now_string2 && now_string2 < end_string2) ? "2" : "0";
if (status == 2) {myshift = 2;}
}
if ($("#shift3start").val() == 'NA NA' && $("#shift3end").val() == 'NA NA') { var status = "CLOSED"}
else {
var timeh3 = time.getHours();
var timem3 = time.getMinutes();
const Start3Time = convertTime12To24($("#shift3start").val());
var s3 = Start3Time.split(':');
const End3Time = convertTime12To24($("#shift3end").val());
var e3 = End3Time.split(':');
var start_time3 = [parseInt(s3[0], 10),0]
var end_time3 = [parseInt(e3[0], 10),0]
var now3 = [timeh3,timem3]
if(end_time3[0] < start_time3[0] && now3[0] < start_time3[0]){
start_time3[0] -= 24;
}else if(start_time3[0] > end_time3[0]){
end_time3[0]+=24;
}
var start_string3 = to_hms_string(start_time3); //the start string converted to a string format. Made comparisons easier.
var end_string3 = to_hms_string(end_time3); //See Above
var now_string3 = to_hms_string(now3); //Above
console.log(start_string3, now_string3, end_string3);
var status = (start_string3 < now_string3 && now_string3 < end_string3) ? "3" : "0";
if (status == 3) {myshift = 3;}
}
if (myshift == 0) {myshift = "CLOSED"}
$('#SHIFT').val(myshift);
$('#lblNameCurShift').text(myshift);
document.cookie = "shift = " + myshift;
return (myshift);
}
showShift();
function convertTime12To24(time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM === "PM" && hours < 12) hours = hours + 12;
if (AMPM === "AM" && hours === 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
return (sHours + ":" + sMinutes);
}
//Function to_hms_string stands for "hour-minute-second" string.
function to_hms_string(timearr){
var minutes = 60+timearr[1];
var hours = "";
if(Math.abs(timearr[0]) < 10){
hours = "0";
}
hours = (timearr[0]<0) ? "-"+hours+Math.abs(timearr[0]) : hours+timearr[0];
return hours+":"+minutes;
}
</script>
It is 4:11PM here now but my output is shown as 'Good Morning' - why is this happening?
$(document).ready(function() {
function dateTime() {
var ndate = new Date();
var h = ndate.getHours() % 12;
var format = h >= 12 ? 'PM' : 'AM';
var m = ndate.getMinutes().toString();
var s = ndate.getSeconds().toString();
if (h < 12) {
h = "0" + h;
$("h3.day-message").html("Good Morning");
} else if (h < 18) {
$("h3.day-message").html("Good Afternoon");
} else {
$("h3.day-message").html("Good Evening");
}
if (s < 10) {
s = "0" + s;
}
if (m < 10) {
m = "0" + m;
}
$('.date').html(h + ":" + m + ":" + s + format);
}
setInterval(dateTime, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>
The issue is because you are using the modulo operator. This means that your h > 12 check will never be hit as the remainder of the division cannot be greater than 12. It's because of this your logic always believes it's still the morning. To fix this, just use a simple < check when comparing the hour figure.
Also note that you have some issues with the formatting of the date, such as appending extra zeroes so you end up with 011 as hour values. You can fix this by using slice().
With all that said, try this:
$(document).ready(function() {
function dateTime() {
var ndate = new Date();
var hours = ndate.getHours();
var message = hours < 12 ? 'Good Morning' : hours < 18 ? 'Good Afternoon' : 'Good Evening';
$("h3.day-message").text(message);
$('.date').html(hours.leadingZeroes(2) + ":" + ndate.getMinutes().leadingZeroes(2) + ":" + ndate.getSeconds().leadingZeroes(2) + (hours < 12 ? 'AM' : 'PM'));
}
setInterval(dateTime, 1000);
});
Number.prototype.leadingZeroes = function(len) {
return (new Array(len).fill('0', 0).join('') + this).slice(-Math.abs(len));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>
$(document).ready(function() {
function dateTime() {
var format="";
var ndate = new Date();
var hr = ndate.getHours();
var h = hr % 12;
if (hr < 12)
{
greet = 'Good Morning';
format='AM';
}
else if (hr >= 12 && hr <= 17)
{
greet = 'Good Afternoon';
format='PM';
}
else if (hr >= 17 && hr <= 24)
greet = 'Good Evening';
var m = ndate.getMinutes().toString();
var s = ndate.getSeconds().toString();
if (h < 12) {
h = "0" + h;
$("h3.day-message").html(greet);
} else if (h < 18) {
$("h3.day-message").html(greet);
} else {
$("h3.day-message").html(greet);
}
if (s < 10) {
s = "0" + s;
}
if (m < 10) {
m = "0" + m;
}
$('.date').html(h + ":" + m + ":" + s + format);
}
setInterval(dateTime, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>
You are calculating mode, so h will never be greater that 12
So, Instead of
var h = ndate.getHours() % 12;
Use it
var h = ndate.getHours();
Explaination: modulo operator(%) will divide total hours by 12 and return the Remainder.
For example if current time is 4 pm, I'll be 16 hours, so It'll return 4
Without jQuery
const messages = [
{ ampm: "am", "greet": 'Good Morning' },
{ ampm: "pm", "greet": 'Good Afternoon' },
{ ampm: "pm", "greet": 'Good Evening' }
];
window.addEventListener("DOMContentLoaded", () => {
const dateSpan = document.getElementById("date");
const message = document.getElementById("day-message");
const dateTime = () => {
let now = new Date(),
hour = now.getHours(),
hh = hour % 12, // (hour % 12).toString().padStart(2,"0") if you want leading 0
mm = now.getMinutes().toString().padStart(2,"0"),
ss = now.getSeconds(),
period = 0;
if (hour < 12) period = 0;
else if (hour >= 12 && hour < 17) period = 1;
else if (hour >= 17 && hour <= 24) period = 2;
message.textContent = messages[period].greet;
dateSpan.textContent = `${hh}:${mm}${messages[period].ampm}`;
};
setInterval(dateTime, 500);
});
<h3 id="day-message"></h3>
<span id="date"></span>
Display Good Morning/Afternoon/Evening using javascript in 12hours format
const displayGreeting =()=>{
const myDate = new Date();
const hrs = myDate.getHours();
let greet;
if (hrs < 12)
greet = 'Good Morning';
else if (hrs >= 12 && hrs <= 17)
greet = 'Good Afternoon';
else if (hrs >= 17 && hrs <= 24)
greet = 'Good Evening';
return greet
}
I need one help .I need to get proper time interval format using Javascript/Jquery.
JS :
document.getElementById('btn').onclick=function(){
var num=6;
var sTime=9;
var duration=1;
var arr = [],
endTime,
startTime = sTime;
for (var i = 0; i < num; i++) {
endTime = startTime + duration;
var inp = document.createElement("input");
inp.type = "text";
var ampm = startTime <= 12 && endTime <= 12 ? " AM " : " PM "
inp.setAttribute("placeholder", startTime + ampm + endTime + ampm);
document.body.appendChild(inp);
startTime = endTime;
}
}
Here i need after 12 o clock it should be 1,2...AM/PM .In my case its coming 13 after 12PM.Here is the Plunkr link to check.Please help me.
Simple demonstration:
for(var num = 0;num<24;num++)
console.log(
num % 12 ?
(num < 12 ? num % 12 + 'AM': num % 12 + 'PM') :
(num==0?'12AM':'12PM'));
Or as function:
function to12h(hour24) {
if (hour24 % 12) {
return hour24 ? /*noon*/ '12 PM' : /*midnight*/ '12 AM';
}
return num < 12 ? num % 12 + ' AM': num % 12 + ' PM';
}
Or you can get it sepatately:
var ampm = num < 12 ? 'AM' : 'PM';
var h12 = num % 12 || 12;
Plunker
I have a Javascript countdown from 12am to 9pm each day and then resets itself.
I want the countdown to go from 8am-9pm instead of 12am-9pm. I have been fiddling with this but I can't seem to make it work with a start time other than the defaulted 12am.
My question is how can I make the countdown from 8-21 hours instead of 0-21 hours?
Javascript:
if (document.getElementById('countdown')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown(){
var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 7) ) { // Monday to Sunday
var target = 21; // 21:00hrs is the cut-off point
if (now.getHours() < target) { //
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdown').innerHTML = str;
}
else
$('.wereOpen').hide();
}
}
var timerRunning = setInterval('countDown()', 1000);
}
Website
I don't fully understand your question, but could you just add now.getHours() >= 7 to your if statement, i.e.
...
if (now.getHours() >= 7 && now.getHours() < target) {
...
} else {
$('.wereOpen').hide();
}
...
EDIT
In light of the comment, the following should work:
if (document.getElementById('countdown')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown(){
var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 7) ) { // Monday to Sunday
var target = 21; // 21:00hrs is the cut-off point
var hours = now.getHours(); //get hours
if(hours < 8 || hours >= target) {
$('.wereOpen').hide();
return;
} else
$('.wereOpen').show();
var hrs = (target - 1) - hours;
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdown').innerHTML = str;
}
}
var timerRunning = setInterval('countDown()', 1000);
}
I've been trying to make a simple javascript code that displays the time, but when I set the array and attach it to the currentDay it appears as 'NaN' can y'all help me out please? =] Here's the code:
function updateTime(){
var currentTime = new Date();
var Wordday = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
var hours = currentTime.getHours()
if ( hours == 0 ) {
hours = "0" ? 12 : hours
};
var minutes = currentTime.getMinutes();
if (minutes < 10){
minutes = "0" + minutes;
};
var seconds = currentTime.getSeconds();
if (seconds < 10){
seconds = "0" + seconds;
};
var day = currentTime.getDay();
var t_str = + Wordday[day] + " " + hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
t_str += "AM";
} else {
t_str += "PM";
};
document.getElementById('time_span').innerHTML = t_str;
}
setInterval(updateTime, 1000);
replace
var t_str = + Wordday[day] +....
with
var t_str = Wordday[day] +...
Now it is working fine for me
One problem is at
if (currentTime.getHours() < 12) {
t_str += "AM";
} else {
t_str += "PM";
};
Demo: Fiddle