I'm currently using this function to calculate 2 fields and the results are good but sometimes missing a zero. sample
10:20 + 10:30 current output 0.10
10:20 + 10:30 I want the output to be 00.10
$(function () {
function calculate() {
time1 = $("#start").val().split(':'),
time2 = $("#end").val().split(':');
hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10);
hours = hours2 - hours1,
mins = 0;
if(hours < 0) hours = 24 + hours;
if(mins2 >= mins1) {
mins = mins2 - mins1;
} else {
mins = (mins2 + 60) - mins1;
}
// the result
$("#hours").val(hours + ':' + mins);
}
});
also when there is an invalid character I keep getting a nan message is possible to change this to 00 instead?
Instead of dealing with the strings and each value independently, you can use the javascript Date object to calculate the difference...
function calculate() {
// Get time values and convert them to javascript Date objects.
var time1 = new Date('01/01/2017 ' + $('#start').val());
var time2 = new Date('01/01/2017 ' + $('#end').val());
// Get the time difference in minutes. If is negative, add 24 hours.
var hourDiff = (time2 - time1) / 60000;
hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
// Calculate hours and minutes.
var hours = Math.floor(hourDiff/60);
var minutes = Math.floor(hourDiff%60);
// Set the result adding '0' to the left if needed
$("#hours").val((hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes));
}
Or even better, you can make the function independent of the DOM elements, so you can reuse it...
function calculate(startTime,endTime) {
// Get time values and convert them to javascript Date objects.
var time1 = new Date('01/01/2017 ' + startTime);
var time2 = new Date('01/01/2017 ' + endTime);
// Get the time difference in minutes. If is negative, add 24 hours.
var hourDiff = (time2 - time1) / 60000;
hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
// Calculate hours and minutes.
var hours = Math.floor(hourDiff/60);
var minutes = Math.floor(hourDiff%60);
// Return the response, adding '0' to the left of each field if needed.
return (hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes);
}
// Now you can use the function.
$("#hours").val(calculate($('#start').val(),$('#end').val()));
Add a function
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
and call this function before displaying result
I propose you that :
$(".calculator").on("change",function(){
var isNegative = false;
var hours = "00:00";
var inputStart = $("#start").val();
var inputEnd = $("#end").val();
if(inputStart!="" && inputEnd != ""){
// calculate only if the 2 fields have inputs
// convert to seconds (more convenient)
var seconds1 = stringToSeconds(inputStart);
var seconds2 = stringToSeconds(inputEnd);
var secondsDiff = seconds2 - seconds1;
var milliDiffs = secondsDiff * 1000;
if(milliDiffs < 0){
milliDiffs = milliDiffs *-1;
isNegative = true;
}
// Convert the difference to date
var diff = new Date(milliDiffs);
// convert the date to string
hours = diff.toUTCString();
// extract the time information in the string 00:00:00
var regex = new RegExp(/[0-9]{2}:[0-9]{2}:[0-9]{2}/);
var arr = hours.match(regex);
hours = arr[0];
// Take only hours and minutes and leave the seconds
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
// put minus in front if negative
if(isNegative){
hours = "-"+hours;
}
// Show the result
$("#hours").val(hours);
// Put back the inputs times in case there were somehow wrong
// (it's the same process)
var date1 = new Date(seconds1*1000);
var str1 = date1.toUTCString();
arr = str1.match(regex);
hours = arr[0];
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
$("#start").val(hours);
// idem for time 2
var date2 = new Date(seconds2*1000);
var str2 = date2.toUTCString();
arr = str2.match(regex);
hours = arr[0];
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
$("#end").val(hours);
}
});
function timeElementToString(timeElement){
var output = timeElement.toString();
if(timeElement < 10 && timeElement >=0)
output = "0"+output;
else if(timeElement < 0 && timeElement >=-10)
output = "-0"+Math.abs(output);
return output;
}
function stringToSeconds(input){
var hours = 0;
var arr=input.split(":");
if(arr.length==2){
hours=parseInt(arr[0]);
minutes=parseInt(arr[1]);
if(isNaN(hours)){
hours = 0;
}
if(isNaN(minutes)){
minutes = 0;
}
}
return hours*3600+60*minutes;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="start">Start</label><input type="text" id="start" class="calculator"></input><br />
<label for="end">End</label><input type="text" id="end" class="calculator"></input><br />
<label for="hours">Hours</label><input type="text" id="hours" readonly="readonly"></input>
</form>
Related
I want to generate a list of time slots with an interval of 15 minutes. Now, like Googles calendar for example, I want it to start at 12:00am and after 12:00pm it should display 1:00am until 11:45am.
Here is what I got so far:
let x = 15;
let times = [];
let tt = 0;
let ap = ["AM", "PM"];
for (let i = 0; tt < 24 * 60; i++) {
let hh = Math.floor(tt / 60);
let mm = tt % 60;
times[i] = ("0" + (hh % 12)).slice(-2) + ":" + ("0" + mm).slice(-2) + ap[Math.floor(hh / 12)];
tt = tt + x;
}
console.log(times)
I created a jsfiddle to see it.
Like mentioned before I would like it to start at 12:00am and instead of 00:00pm it should display 12:00pm, then 12:15pm, then 12:30pm etc. etc.
How can I achieve that?
You can check if hh % 12 is equal 0:
let x = 15; //minutes interval
let times = []; // time array
let tt = 0; // start time
let ap = ["AM", "PM"]; // AM-PM
//loop to increment the time and push results in array
for (let i = 0; tt < 24 * 60; i++) {
let hh = Math.floor(tt / 60); // getting hours of day in 0-24 format
let mm = tt % 60; // getting minutes of the hour in 0-55 format
let hh12 = hh % 12;
if( hh12 === 0) {
hh12 = 12;
}
times[i] = ("0" + (hh12)).slice(-2) + ":" + ("0" + mm).slice(-2) + ap[Math.floor(hh / 12)]; // pushing data in array in [00:00 - 12:00 AM/PM format]
tt = tt + x;
}
console.log(times);
You could create a start date (at whichever time you wish), then keep adding your interval in minutes until you hit your desired end time (I'm assuming we'll generate slots for the whole day):
let date = new Date(2021, 1, 10, 12, 0, 0);
const intervalMinutes = 15;
const dom = date.getDate();
let times = [];
do {
times.push(date.toLocaleTimeString("en-US", { hour: '2-digit', minute: '2-digit' }))
date = new Date(date.setMinutes(date.getMinutes() + intervalMinutes));
} while (date.getDate() === dom)
console.log("Time slots:",times);
I've been trying to implement the function that sums two values as hours.
"Example: 01:30 + 00:30 = 02:00"
So I have this function below that works only if the sum of the two values is equal to a round number such as the example above. But the problem is when the values are say 01:45 + 00:20 it gives me 33:05 instead of 02:05.
I've tried several combinations but nothing has worked so far.
function sumOFHoursWorked(){
var time1 = "00:45";
var time2 = "01:20";
var hour=0;
var minute=0;
var second=0;
var splitTime1= time1.split(':');
var splitTime2= time2.split(':');
hour = parseInt(splitTime1[0])+parseInt(splitTime2[0]);
minute = parseInt(splitTime1[1])+parseInt(splitTime2[1]);
hour = hour + minute/60;
minute = minute%60;
second = parseInt(splitTime1[2])+parseInt(splitTime2[2]);
minute = minute + second/60;
second = second%60;
var REalhourstime = ('0' + hour).slice(-2)+':'+('0' + minute).slice(-2);
alert(REalhourstime);
document.getElementById('realhorasTB').innerHTML = REalhourstime;
}
It actually depends on how your time will be, i mean it will be in mm:ss formet or hh:mm:ss or maybe hh:mm:ss:msms but for just simple second and minutes you can do something like this
function sumOFHoursWorked(){
var time1 = "00:45".split(':');
var time2 = "01:20".split(':');
let secondSum = Number(time1[1]) + Number(time2[1]);
let minSum = Number(time1[0]) + Number(time2[0]);
if(secondSum > 59){
secondSum = Math.abs(60 - secondSum);
minSum += 1;
}
if(secondSum < 10){
secondSum = `0${secondSum}`;
}
if(minSum < 10){
minSum = `0${minSum}`;
}
return `${minSum}:${secondSum}`;
}
console.log(sumOFHoursWorked());
I would convert it to minutes and subtract and then calculate hours and minutes.
function totalMinutes (time) {
var parts = time.split(":")
return +parts[0] * 60 + +parts[1]
}
function timeDiff (time1, time2) {
var mins1 = totalMinutes(time1)
var mins2 = totalMinutes(time2)
var diff = mins2 - mins1
var hours = '0' + (Math.floor(diff/60))
var minutes = '0' + (diff - hours * 60)
return (hours.slice(-2) + ':' + minutes.slice(-2))
}
console.log(timeDiff("00:45", "01:20"))
It will fail for times that go over midnight, a simple less than check can fix that.
function totalMinutes (time) {
var parts = time.split(":")
return +parts[0] * 60 + +parts[1]
}
function timeDiff (time1, time2) {
var mins1 = totalMinutes(time1)
var mins2 = totalMinutes(time2)
if (mins2 < mins1) {
mins2 += 1440
}
var diff = mins2 - mins1
var hours = '0' + (Math.floor(diff/60))
var minutes = '0' + (diff - hours * 60)
return (hours.slice(-2) + ':' + minutes.slice(-2))
}
console.log(timeDiff("23:45", "00:45"))
First of all, the time1 and time2 strings are missing the seconds at the end. For example, var time1 = "00:45:00". Otherwise, your calculation will have some NaN values.
The main issue is that hour is a floating point number (~ 2.083333333333333), so ('0' + hour) is '02.083333333333333'.
You could use something like this instead: ('0' + Math.floor(hour)).
In one of my projects i have to calculate the difference between two times. For example the work hours starts at 6:30 and finishes at 10 o'clock. The difference is 3 hours and 30 minutes. I write a small JS function to handles the task and it works great, gives me the following result: 3.5.
I tried .format("HH:mm") but the result was undefined not a function.
Is there any method that converts the output like "HH:mm"?
Here is the dateDiff function:
function dateDiff() {
var startTime = moment(document.getElementById("startTime").value, "HH:mm");
var endTime = moment(document.getElementById("end").value, "HH:mm");
var duration = moment.duration(endTime.diff(startTime));
var hours = duration.asHours();
console.log(hours);
document.getElementById('dateDiffResult').value = moment(hours);
}
You could just get the hours and minutes separately and format the string:
function dateDiff() {
var startTime = moment(document.getElementById("startTime").value, "HH:mm");
var endTime = moment(document.getElementById("end").value, "HH:mm");
var duration = moment.duration(endTime.diff(startTime));
var hours = duration.hours();
var minutes = duration.minutes();
document.getElementById('dateDiffResult').value = hours +":"+ minutes;
}
if your function works and gives you the time difference in hours, surely it is then simple to calculate the hours and minutes from the number of hours? Using your stated difference of 3.5...
var diff=3.5;
var hour=Math.floor(diff);//gives hour=3;
var hours=("0"+ hour).slice(-2);//pads the hours with a leading zero if required to give hours=03;
var minute = (diff-hour)*60;//gives 30
var minutes=("0"+ minute ).slice(-2);//pads the minutes with a leading zero if required to give minutes=30;
var totalDiff= hours + ":" +minutes; //gives 03:30 as in HH:MM
I added the following to demonstrate this in the snippet:
$(document).ready
(function(){
var diff=3.5;
var hour=Math.floor(diff);//gives hour=3;
var hours=("0"+ hour).slice(-2);//gives hours=03;
var minute = (diff-hour)*60;//gives 30
var minutes=("0"+ minute ).slice(-2);//gives minutes=30;
var totalDiff= hours + ":" +minutes; //gives 03:30 as in HH:MM
alert("HH:MM: " + totalDiff);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Using a time-field jQuery plugin, you can generate time fields. After that, you can listen to changes to the fields and update the hours difference accordingly.
(function($) {
$.initTimeFields = function(interval) {
$('.time-field').each(function(_, field) {
$(field).initTimeField(interval);
});
};
$.fn.initTimeField = function(interval) {
var hour = 0, minute = 0, diff;
while (hour < 24 && minute < 60) {
this.append($('<option>', {
val : hour * 60 + minute,
text : ('00' + hour).substr(-2) + ':' + ('00' + minute).substr(-2)
}));
minute += interval;
diff = minute - 60;
if (diff >= 0) {
hour += 1;
minute %= 60;
}
}
var value = this.data('value') || 0;
if (typeof value === 'string' && value.indexOf(':') > -1) {
value = (function(values) {
return parseInt(values[0], 10) * 60 + parseInt(values[1], 10);
}(value.split(':')));
}
this.val(value);
};
}(jQuery));
function updateTimeDiff() {
$('#hour-diff').val(calcHourDiff(getTime('#start-time'), getTime('#end-time')) + ' hours');
}
function calcHourDiff(startTime, endTime) {
var diff = moment.duration(endTime.diff(startTime));
return ('00' + diff.hours()).substr(-2) + ':' + ('00' + diff.minutes()).substr(-2);
}
function getTime(selector) {
return moment($(selector).find('option:selected').text(), "HH:mm");
}
$('.time-field').on('change', function() {
updateTimeDiff()
});
// Main
$.initTimeFields(15);
$('.time-field').trigger('change');
label { display: inline-block; width: 3em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<label>Start: </label><select id="start-time" class="time-field" data-value="06:30"></select><br />
<label>End: </label><select id="end-time" class="time-field" data-value="10:00"></select><br />
<label>Diff: </label><input id="hour-diff" type="text" size="8" />
I want to subtract the two different 24 hours time format.
I had tried with following :
var startingTimeValue = 04:40;
var endTimeValue = 00:55;
var hour = startingTimeValue.split(":");
var hour1 = endTimeValue.split(":");
var th = 1 * hour[0] - 1 * hour1[0];
var tm = 1 * hour[1] - 1 * hour1[1];
var time = th+":"+tm;
This code is working fine if second minutes is not greater than the first.but other case it will return minus values.
The above code sample values result :
time1 : 04:40
time2 : 00:55
The result should be : 03:45 (h:mi) format.
But right now I am getting 04:-5 with minus value.
I had tried with the link as : subtract minutes from calculated time javascript but this is not working with 00:00 format.
So how to calculate the result value and convert into hours and minutes?
I would try something like the following.
The way I see it, it is always better to break it down to a common unit and then do simple math.
function diffHours (h1, h2) {
/* Converts "hh:mm" format to a total in minutes */
function toMinutes (hh) {
hh = hh.split(':');
return (parseInt(hh[0], 10) * 60) + parseInt(hh[1], 10);
}
/* Converts total in minutes to "hh:mm" format */
function toText (m) {
var minutes = m % 60;
var hours = Math.floor(m / 60);
minutes = (minutes < 10 ? '0' : '') + minutes;
hours = (hours < 10 ? '0' : '') + hours;
return hours + ':' + minutes;
}
h1 = toMinutes(h1);
h2 = toMinutes(h2);
var diff = h2 - h1;
return toText(diff);
}
Try:
var time1 = Date.UTC(0,0,0,4,40,0);
var time2 = Date.UTC(0,0,0,0,55,0);
var subtractedValue = time1 - time2;
var timeResult = new Date(subtractedValue);
console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
DEMO
This solution utilizes javascript built-in date. How it works:
var time1 = Date.UTC(0,0,0,4,40,0);
var time2 = Date.UTC(0,0,0,0,55,0);
time1, time2 is the number of miliseconds since 01/01/1970 00:00:00 UTC.
var subtractedValue = time1 - time2;
subtractedValue is the difference in miliseconds.
var timeResult = new Date(subtractedValue);
console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
These lines reconstruct a date object to get hours and minutes.
This works better , A fiddle I just found
var difference = Math.abs(toSeconds(a) - toSeconds(b));
fiddle
This method may work for you:
function timeDiff(s,e){
var startTime = new Date("1/1/1900 " + s);
var endTime = new Date("1/1/1900 " + e);
var diff = startTime - endTime;
var result = new Date(diff);
var h = result.getUTCHours();
var m = result.getUTCMinutes();
return (h<=9 ? '0' + h : h) + ':' + (m <= 9 ? '0' + m : m);
}
var startingTimeValue = "04:40";
var endTimeValue = "00:55";
var formattedDifference = timeDiff(startingTimeValue,endTimeValue);
Demo: http://jsfiddle.net/zRVSg/
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));