I am using js to render a 12 hour digital clock that continuously updates. However, the code I found online left me with a 24 hour clock and the wrong am/pm output. Right now it shows 13:33 am. I have tried out other snippets of code here and there, some jquery examples, but nothing worked and a lot of css already went into this one. How would I convert this to a properly functioning 12 hour clock? Thanks!
$(document).ready(function() {
setInterval(function() {
// Create a newDate() object and extract the hours of the current time on the visitor's
var hours = new Date().getHours();
// Add a leading zero to the hours value
$(".hours").html((hours < 10 ? "0" : "") + hours);
}, 1000);
});
setInterval(function() {
// Create a newDate() object and extract the minutes of the current time on the visitor's
var minutes = new Date().getMinutes();
// Add a leading zero to the minutes value
$(".min").html((minutes < 10 ? "0" : "") + minutes);
}, 1000);
setInterval(function() {
var time = new Date().getHours();
var time = (time + 24 - 2) % 24;
var mid = 'am';
if (time == 0) { //At 00 hours we need to show 12 am
hours = 12;
} else if (time > 12) {
time = time % 12;
mid = 'pm';
}
$(".ap").html(mid);
});
ul {
list-style: none;
}
li {
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clock">
<ul>
<li class="hours"></li>
<li class="point">:</li>
<li class="min"></li>
<li class="ap"></li>
</ul>
</div>
First problem is with this line:
var hours = new Date().getHours();
It takes the current hours which will be from 0 to 23. For example:
var hours = new Date('2020-01-01 16:00:00').getHours();
console.log(hours);
You need to convert this to 1-12 range by using the modulo operator:
var hours = new Date('2020-01-01 16:00:00').getHours() % 12;
console.log(hours);
The only thing needed is to make sure that midnight is shown as 12:
var hours = new Date('2020-01-01 00:00:00').getHours() % 12;
if (hours === 0) {
hours = 12;
}
console.log(hours);
Second problem is when determining AM or PM.
var time = (time + 24 - 2) % 24;
is wrong the -2 offset makes any hour incorrect:
var time = 16;
time = (time + 24 - 2) % 24;
console.log(time);
var time = 1;
time = (time + 24 - 2) % 24;
console.log(time);
Next, adding 24 to the hours is useless. Finally, the modulo 24 operation is unneeded once the +24 offset is removed. In effect the entire line throws off all calculations. You need to remove it.
There is other logic that tries to properly format the hours but it's misplaced, since this code never sets the hours - that's already set elesewhere. This code only sets the AM/PM.
Lastly, the third setInterval is missing an interval value. Technically, that will still work but it will run the function very often. Based on the other setInterval invocations, it seems the intent is to have a delay of 1000 (it's in milliseconds).
When all of this is done, here is what the code looks like:
$(document).ready(function() {
setInterval(function() {
// Create a newDate() object and extract the hours of the current time on the visitor's
var hours = new Date().getHours() % 12;
//At 00 hours we need to show 12 am
if (hours === 0) {
hours = 12
}
// Add a leading zero to the hours value
$(".hours").html((hours < 10 ? "0" : "") + hours);
}, 1000);
});
setInterval(function() {
// Create a newDate() object and extract the minutes of the current time on the visitor's
var minutes = new Date().getMinutes();
// Add a leading zero to the minutes value
$(".min").html((minutes < 10 ? "0" : "") + minutes);
}, 1000);
setInterval(function() {
var time = new Date().getHours();
var mid = 'am';
if (time > 12) {
mid = 'pm';
}
$(".ap").html(mid);
}, 1000);
li {
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clock">
<ul>
<li class="hours"></li>
<li class="point">:</li>
<li class="min"></li>
<li class="ap"></li>
</ul>
</div>
Here's a function that'll be helpful. It takes military hours and minutes in the form of numbers and returns an array of 12-hour time components (the hour, the minutes, and the am/pm).
function get12HourTimeComponents(hours, minutes) {
minutes = (minutes < 10 ? "0" : "") + minutes;
if (hours % 12 == 0) return [12, minutes, hours == 12 ? "pm" : "am"];
return [hours % 12, minutes, hours < 12 ? "am" : "pm"];
}
console.log(get12HourTimeComponents(15, 23));
The first line adds a leading 0 to minutes if needed. The second line handles cases where the hour is 0 or 12 specifically (because they don't work well with the % operator in the third line). The third line returns an array for all other cases while converting hours to 12-hour format and checking if hours indicate "am" or "pm". To implement this in your code, you'd do this:
function get12HourTimeComponents(hours, minutes) {
minutes = (minutes < 10 ? "0" : "") + minutes;
if (hours % 12 == 0) return [12, minutes, hours == 12 ? "pm" : "am"];
return [hours % 12, minutes, hours < 12 ? "am" : "pm"];
}
function showTime() {
var date = new Date();
var twelveHourTimeComponents = get12HourTimeComponents(date.getHours(), date.getMinutes());
$(".hours").html(twelveHourTimeComponents[0]);
$(".min").html(twelveHourTimeComponents[1]);
$(".ap").html(twelveHourTimeComponents[2]);
}
$(document).ready(function() {
showTime(); //show time immediately when page loads
setInterval(showTime, 1000); //and every second after that
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="clock">
<ul>
<li class="hours"></li>
<li class="point">:</li>
<li class="min"></li>
<li class="ap"></li>
</ul>
</div>
I'm assuming you have your own CSS to style this, so I left that alone. You'll notice that I got rid of a bunch of intervals. You only need the one. You can update everything once per second with a single interval. If this is not enough explanation and you have questions, please let me know by leaving a comment.
Related
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.
I have an assignment where we have to plugin the time in a 12 hour format through a function in a js file. I have the function written but the HTML is not picking it up and the function is returning a null value.
If I layout the function between script tags in the HTML file it will return the time fine but I need it to be styled for the assignment and also it has to be in a separate js file.
/*here is the js file*/
"use strict";
var $ = function(id) { return document.getElementById(id); };
var displayCurrentTime = function() {
//GET CURRENT DATE-TIME
var currentTime = new Date ();
//GET THE CURRENT TIME
var hours = currentTime.getHours ();
var minutes = currentTime.getMinutes ();
var seconds = currentTime.getSeconds ();
//APPEND A ZERO(0) IF MINUTES OR SECONDS ARE LESS THAN 10
minutes = ( minutes < 10 ? "0" : "" ) + minutes;
seconds = ( seconds < 10 ? "0" : "" ) + seconds;
//CHOOSE AM IF HOUR IS LESS THAN 12 AND PM IF HOUR IS BIGGER THAN 12
var ampm = ( hours < 12 ) ? "AM" : "PM";
//CHANGE TO 12 HOUR FORMAT BY SUBTRACTING 12 IF HOUR IS BIGGER THAN 12.
hours = ( hours > 12 ) ? hours - 12 : hours;
//CHANGE HOUR OF 0 (MIDNIGHT) TO 12.
hours = ( hours == 0 ) ? 12 : hours;
//CREATE STRING OF TIME
var currentTimeString = hours + ":" + minutes + ":" + seconds + " " + ampm;
//DISPLAY TIME IN DIV
document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}
var displayCurrentTime = $("minutes");
console.log(displayCurrentTime);
var padSingleDigit = function(num) {
if (num < 10) { return "0" + num; }
else { return num; }
};
window.onload = function() {
// set initial clock display and then set interval timer to display
// new time every second. Don't store timer object because it
// won't be needed - clock will just run.
displayCurrentTime(setInterval(1000));
};
There are 4 span ids in the HTML file (hours, minutes, seconds, and ampm) that need to be filled.
Here is the index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Clock</title>
<link rel="stylesheet" href="clock.css">
<script src="clock.js"></script>
</head>
<body>
<main>
<h1>Digital clock</h1>
<fieldset>
<legend>Clock</legend>
<span id="hours"> </span>:
<span id="minutes"> </span>:
<span id="seconds"> </span>
<span id="ampm"> </span>
</fieldset>
</main>
</body>
</html>
There's a few issues that I see that would be tripping you up
1) You defined your function as displayCurrentTime (which works), but then overwrite it completly with the line var displayCurrentTime = $("minutes"). So, instead of calling a function, you're going to retrieve an element
- Your console.log() is right after, so that's why you're seeing a null value
2) You say "4 span ids in the HTML file (hours, minutes, seconds, and ampm) that need to be filled" but your script just returns all of those fields, joined together - that's not helpful to you, but you do have all the correct values already in the function
var displayCurrentTime = function() {
var currentTime = new Date ();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
minutes = ( minutes < 10 ? "0" : "" ) + minutes;
seconds = ( seconds < 10 ? "0" : "" ) + seconds;
var ampm = ( hours < 12 ) ? "AM" : "PM";
hours = ( hours > 12 ) ? hours - 12 : hours;
hours = ( hours == 0 ) ? 12 : hours;
// At this point, all 4 values are ready to drop into your span tags
$('hours').textContent = hours;
$('minutes').textContent = minutes;
$('seconds').textContent = seconds;
$('ampm').textContent = ampm;
}
3) Your setInterval is being called wrong, it should be like
window.onload = function() {
setInterval(displayCurrentTime, 1000);
};
Here is the codepen with these changes
I need a simple countdown timer, but it is really bugging me that I can't seem to get it for some reason, and I think it's because of the special way I need it done, it has to adhere to these rules:
Must be every hour
Must be on the 30 minute mark
Must use UTC time
So for instance, it is 07:22 UTC, it would be 8 minutes till the next one.
If it were say, 07:30, it would say 1 hour till the next one.
And last but not least, if it were 07:31, it would say 59 minutes till the next one.
I was able to do this very easily for other countdowns I made, but those were for on the hour type things, it wasn't this complicated... I'm just stumped big time, please help me.
EDIT
Added sample code
var d = new Date();
var hoursUntil = 2 - d.getUTCHours() % 3;
var minutesUntil = 60 - d.getUTCMinutes();
var timestr = "";
if (minutesUntil === 60) {
hoursUntil++;
minutesUntil = 0;
}
if (hoursUntil > 0) {
timestr += hoursUntil + " hour" + (hoursUntil > 1 ? "s" : "");
}
if (hoursUntil >= 1 && minutesUntil > 1) {
timestr += " and " + minutesUntil + " minute" + (minutesUntil > 1 ? "s" : "");
}
if (minutesUntil > 1 && hoursUntil < 1) {
timestr += minutesUntil + " minute" + (minutesUntil > 0 && minutesUntil < 2 ? "" : "s");
}
bot.sendMessage(msg, "Next event will be in " + timestr + ".");
Let's do some thoughts. What we want to know is, when the minute hand next time shows 30. If we wanted to know only every half hour, we could just take the rest of division by 30 as you did with d.getUTCHours() % 3.
However, we want to get every 60 minutes, so we have do do somethingInMinutes % 60. The mark must be on shift from 60 to 0, so just add 30 minutes.
To have seconds precision, calculate that into seconds, add the current seconds and subtract both from 60 minutes (3600 seconds).
We want a timer that triggers on every second shift. Calculate the difference of 1000 and milliseconds.
<div>Seconds remaining until next 30 minutes mark: <span id="min-total"></span></div>
<div>minutes:seconds remaining: <span id="min-part"></span>:<span id="sec-part"></span></div>
<script>
var byId = document.getElementById.bind(document);
function updateTime()
{
var
time = new Date(),
// take 1800 seconds (30 minutes) and substract the remaining minutes and seconds
// 30 minutes mark is rest of (+30 divided by 60); *60 in seconds; substract both, mins & secs
secsRemaining = 3600 - (time.getUTCMinutes()+30)%60 * 60 - time.getUTCSeconds(),
// integer division
mins = Math.floor(secsRemaining / 60),
secs = secsRemaining % 60
;
byId('min-total').textContent = secsRemaining;
byId('min-part').textContent = mins;
byId('sec-part').textContent = secs;
// let's be sophisticated and get a fresh time object
// to calculate the next seconds shift of the clock
setTimeout( updateTime, 1000 - (new Date()).getUTCMilliseconds() );
}
updateTime();
</script>
Maybe I am missing something but as far as I can see, UTC and in fact hours in general are not relevant to this. It should be as simple as just calculating where the current minute is.
Maybe something like
now = new Date();
minutes = now.getMinutes();
if(minutes > 30) {
minutes_until = (60 - minutes) + 30;
}
else {
minutes_until = 30 - minutes;
}
How do i go about calculating the duration between two times in HHMM format by Javascript.
The input format will always be HHMM
The input time will always be for the same day.
Thank you for your inputs.
------------------- lame attemp --------------------
<html>
<div>
STA:<input type="text" id="STA" onClick="timed();"> ATA: <input type="text"
id="ATA"onClick="timed();">
DIFF: <input type="text" id="DIFF" onClick="timed();">
</div>
<div></div>
</html>
<script>
function timed(){
var x=0;
var y=0;
var o=0;
var l=0;
var a=0;
var b=0;
o=document.getElementById("STA").value;
l=document.getElementById("ATA").value;
a=o/100;
b=l/100;
x=a.split('.');
y=b.split('.');
document.getElementById("DIFF").value=x[0]-y[0]+":"+x[1]-y[1];
}
</script>
Have a look at this script:
It works using the input you say is provided the HHMM format.
function timed(){
var time1 = document.getElementById("STA").value;
var time2 = document.getElementById("ATA").value;
if ( time1.match(/^[0-9]{4}$/g) && time2.match(/^[0-9]{4}$/g) )
{
//lets calculate the difference. But values consist of four digits.
var time1Seconds = toSeconds(time1.substr(0,2), time1.substr(2));
var time2Seconds = toSeconds(time2.substr(0,2), time2.substr(2));
if (!time1Seconds || !time2Seconds)
{
//input is not correct.
return false;
}
var difference = time1Seconds - time2Seconds;
if (difference < 0)
{
difference = Math.abs(difference);
}
var hours = parseInt(difference/3600)
hours = hours < 10 ? "0" + hours : hours;
var minutes = parseInt((difference/3600) % 1 *60)
minutes = minutes < 10 ? "0" + minutes : minutes;
document.getElementById("DIFF").value = hours + ":" + minutes;
}
}
function toSeconds(hours, minutes)
{
var seconds = 0;
if ( (hours >= 0 && hours < 24) && (minutes >= 0 && minutes < 60))
{
seconds += (parseInt(hours)*3600) + (parseInt(minutes)*60);
return seconds
}
else
{
return false;
}
}
How it works.
It retrieves the values from the inputs. Then it checks if both inputs have numeric input that is exactly 4 digits long. If not this function doesn't return anything.
Second divide the string into two sections. Hours and minutes for both inputs. Convert them to seconds by using toSeconds. This functions checks if the hours and minutes are valid, if not this function returns false. When both converted times are not false the function continues. It subtracts the values from each other. If the value is lower than zero convert it to a positive. Then convert the seconds back to hours and minutes and display in the difference input. Enjoy.
I have two sets of 'select' elements where the user can enter in two times. It looks like this:
Start:
[hour] [minute] [meridian]
End:
[hour] [minute] [meridian]
I'm trying to take those times and figure out the difference. So I can then output:
Difference: 1.25 HRS
The decimal format, as you probably know, means 1 hour and 15 minutes.
There's also a checkbox the user can click which, if selected, will take away 30 minutes. Here's what my current code looks like:
var startHours = parseInt($start.find('.times:eq(0)')[0].value);
var startMinutes = parseInt($start.find('.times:eq(1)')[0].value);
var startMeridian = $start.find('.times:eq(2)')[0].value
if (startMeridian == 'PM')
startHours += 12;
var finishHours = parseInt($finish.find('.times:eq(0)')[0].value);
var finishMinutes = parseInt($finish.find('.times:eq(1)')[0].value);
var finishMeridian = $finish.find('.times:eq(2)')[0].value
if (finishMeridian == 'PM')
finishHours += 12;
// compute the difference
var completeHours = finishHours - startHours;
var completeMinutes = finishMinutes - startMinutes;
var newTime = 0;
if (completeHours < 0 || completeMinutes < 0)
newTime = '0.0';
else
newTime = completeHours + '.' + completeMinutes;
var hadBreak = $parent.parents('tr').next('tr').find('.breakTaken')[0].checked;
if (hadBreak)
{
time = newTime.split('.');
hours = time[0];
minutes = time[1];
minutes = minutes - 30;
if (minutes < 0)
{
minutes = 60 - (minutes * 1);
hours = hours - 1;
}
newTime = (hours < 0) ? '0.0' : hours + '.' + minutes;
}
$parent.parents('tr').next('tr').find('.subtotal')[0].innerHTML = newTime;
total += parseFloat(newTime);
It's failing... What am I doing wrong?
To save you some hassle, I would recommend using the Date object, which is very convenient:
var startDate = new Date(year, month, date, hour, minute, second, millisecond);
var endDate = new Date(year, month, date, hour2, minute2, second2, millisecond2);
// You can skip hours, minutes, seconds and milliseconds if you so choose
var difference = endDate - startDate; // Difference in milliseconds
From there you can calculate the days, hours and minutes that passed between those two dates.
The line
newTime = (hours < 0) ? '0.0' : hours + '.' + minutes;
is wrong - minutes might be 15, but you want it to print out the fraction. Hence you need:
var MinutesDisplay = minutes/60*100;
newTime = (hours < 0) ? '0.0' : hours + '.' + (MinutesDisplay.toFixed(0));