Calculating difference in times in 24 hour time format in Javascript - javascript

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.

Related

What is the purpose of this line of code if (hours == 00) { hours = 12; } please explain to me

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.

12 hour Javascript Clock Showing 24 time, Wrong AM/PM

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.

Trying to write a function to display the time in a 12 hour format but the HTML is not displaying the time and the function returns null

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

How to get of two time values using jQuery/Javascript?

I have two values that are used for the amount of time it will take to complete a task. How can I add these values together to come up with a total number of hours and minutes, but still have the value account for 60 minutes equalling one hour?
The two values I'd like to get the sum of and the total value are in HH:MM (00:00) format.
Thanks!
Writing your own time and date functions can get complex. Why re-invent the wheel. Take a look at the excellent http://www.datejs.com/ date library. It handles all date and time related tasks and usage is very simple.
Here's something I had laying around. It allows for an infinite number of arguments, so you could have addTime('01:00') or addTime('01:00', '02:00', '03:00', '04:00'), etc. It's three functions long because it also verifies if the times entered are properly formatted, and if not, then it formats them. (E.g. Ensures that minutes is 2 digits long, and if hours is 1 digit long, then pad it with one zero, etc.)
You can play with it here: http://jsfiddle.net/WyxwU/
It's also here:
var totalTime = addTime('12:34', '56:12', '78:45');
document.write(totalTime);
function addTime()
{
if (arguments.length < 2)
{
if (arguments.length == 1 && isFormattedDate(arguments[0])) return arguments[0];
else return false;
}
var time1Split, time2Split, totalHours, totalMinutes;
if (isFormattedDate(arguments[0])) var totalTime = arguments[0];
else return false;
for (var i = 1; i < arguments.length; i++)
{
// Add them up
time1Split = totalTime.split(':');
time2Split = arguments[i].split(':');
totalHours = parseInt(time1Split[0]) + parseInt(time2Split[0]);
totalMinutes = parseInt(time1Split[1]) + parseInt(time2Split[1]);
// If total minutes is more than 59, then convert to hours and minutes
if (totalMinutes > 59)
{
totalHours += Math.floor(totalMinutes / 60);
totalMinutes = totalMinutes % 60;
}
totalTime = totalHours + ':' + padWithZeros(totalMinutes);
}
return totalTime;
}
function isFormattedDate(date)
{
var splitDate = date.split(':');
if (splitDate.length == 2 && (parseInt(splitDate[0]) + '').length <= 2 && (parseInt(splitDate[1]) + '').length <= 2) return true;
else return false;
}
function padWithZeros(number)
{
var lengthOfNumber = (parseInt(number) + '').length;
if (lengthOfNumber == 2) return number;
else if (lengthOfNumber == 1) return '0' + number;
else if (lengthOfNumber == 0) return '00';
else return false;
}
Here is the simple JS code for this,
var a = "2:50";
var b = "2:15";
var splitTimeStr = function(t){
var t = t.split(":");
t[0] = Number(t[0]);
t[1] = Number(t[1]);
return t;
};
var addTime = function(t1, t2){
var t1Hr = splitTimeStr(t1)[0];
var t1Min = splitTimeStr(t1)[1];
var t2Hr = splitTimeStr(t2)[0];
var t2Min = splitTimeStr(t2)[1];
var rHr = t1Hr + t2Hr;
var rMin = t1Min + t2Min;
if (rMin >= 60)
{
rMin = rMin - 60;
rHr = rHr + 1;
}
if (rMin < 10) rMin = "0" + rMin;
if (rHr < 10) rHr = "0" + rHr;
return "" + rHr + ":" + rMin;
};
document.write(addTime(a, b));
you can validate/play this with code here: http://jsfiddle.net/z24v7/
What you have to do is calculate them to a decimal by that I mean.
Strip out the hour/mins multiple that by 60 + to mins
//strip out the hours
l_hour = Number(l_time$.substr(0, l_pos));
//Strip out the mins
l_min = Number(l_time$.substr(l_pos + 1, l_time$.length));
//add the two values divided by 60 mins
l_time_decimal= Number(Math.abs(l_hour)) + Number(Math.abs(l_min)/60);
Do this for each value then deduct the two figures to give you the difference (i.e time taken). All thats left is convert it back from a decimal to a time
l_difference_in_min = l_difference * 60;
l_time_mins = l_difference_in_min%60;
l_time_hours = (l_difference_in_min - l_mins)/60;
Now just format the two to be HH:MM
I would break the problem into sub-tasks that are reusable. You have to concerns here:
Process a time string in "hh:mm" format: Converting this to minutes makes sense because it seems to be the time granularity at which you're operating.
Format a given number of minutes into a time string in "hh:mm" format.
The fact that you're adding two times together is a diversion from the actual two problems above.
Parse a time string into minutes:
function parseMinutes(s) {
var tokens = s.split(":");
return tokens[0] * 60 + parseInt(tokens[1]);
}
Format minutes into a time string:
function formatMinutes(minutes) {
function pad(n) {
return n > 9
? n
: ("0" + n);
}
var hours = Math.floor(minutes / 60),
mins = minutes % 60;
return pad(hours) + ":" + pad(mins);
}
Then your specific problem can be tackled by:
var sum = formatMinutes(parseMinutes(a) + parseMinutes(b));

Javascript - How can I work out the difference between two given times? (hours-minutes)

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));

Categories