How can I do sum two time values in javascript - javascript

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

Related

output correct format 24 hour after calculation

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>

How to calculate the time difference using java script?

I'm getting date from the API in this format 14:30:00 inside "this.StartTime". My question is how can I calculate the time difference between the date I'm getting inside "this.StartTime" and present date?
Following is my component.ts code:-
getBookingDetails() {
this._CounsellingService.getBookingDetails().subscribe(
response => {
this.sessionDetails = response;
this.StartTime = this.sessionDetails.StartTime;
}
);
}
You can create a date today and then set its time part as startDate. Then compare it with current time;
var startTime = "14:30:00".split(":");
var h = startTime[0];
var m = startTime[1];
var s = startTime[2];
var now = new Date();
startTime = new Date(now);
startTime.setHours(h);
startTime.setMinutes(m);
startTime.setSeconds(s);
difference = startTime.getTime() - now.getTime();
console.log(msToTime(difference))
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}

calculate time difference between two date in HH:MM:SS javascript

I have created one timer application in javascript.
Firstly it takes the current UTC date to init timer with some reference. here's the code
on_timer: function(e) {
var self = this;
if ($(e.target).hasClass("pt_timer_start")) {
var current_date = this.get_current_UTCDate();
this.project_timesheet_db.set_current_timer_activity({date: current_date});
this.start_interval();
this.initialize_timer();
this.$el.find(".pt_timer_start,.pt_timer_stop").toggleClass("o_hidden");
Now, Once timer is started and after some time span timer has some elapsed time with reference to above on_timer: function(e) function.
This function is
start_interval: function() {
var timer_activity = this.project_timesheet_db.get_current_timer_activity();
var self = this;
this.intervalTimer = setInterval(function(){
self.$el.find(".pt_duration").each(function() {
var el_hour = $(this).find("span.hours");
var el_minute = $(this).find("span.minutes");
var minute = parseInt(el_minute.text());
if(minute >= 60) {
el_hour.text(_.str.sprintf("%02d", parseInt(el_hour.text()) + 1));
minute = 0;
}
el_minute.text(_.str.sprintf("%02d", minute));
var el_second = $(this).find("span.seconds");
var seconds = parseInt(el_second.text()) + 1;
if(seconds > 60) {
el_minute.text(_.str.sprintf("%02d", parseInt(el_minute.text()) + 1));
seconds = 0;
}
el_second.text(_.str.sprintf("%02d", seconds));
});
}, 1000);
},
Now, considering el_hour, el_minute, el_seconds How to can i count time difference between init time and current timer value in HH:MM:SS manner.
thanks in advance for help
To convert H:M:S to seconds, you can use a simple function like:
// Convert H:M:S to seconds
// Seconds are optional (i.e. n:n is treated as h:s)
function hmsToSeconds(s) {
var b = s.split(':');
return b[0]*3600 + b[1]*60 + (+b[2] || 0);
}
Then to convert seconds back to HMS:
// Convert seconds to hh:mm:ss
// Allow for -ve time values
function secondsToHMS(secs) {
function z(n){return (n<10?'0':'') + n;}
var sign = secs < 0? '-':'';
secs = Math.abs(secs);
return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0) + ':' + z(secs%60);
}
var a = '01:43:28';
var b = '12:22:46';
console.log(secondsToHMS(hmsToSeconds(a) - hmsToSeconds(b))); // -10:39:18
console.log(secondsToHMS(hmsToSeconds(b) - hmsToSeconds(a))); // 10:39:18
You may want to abbreviate the function names to say:
toHMS(toSec(a) - toSec(b)); // -10:39:18
Note that this doesn't cover where the time may cross a daylight saving boundary. For that you need fully qualified dates that include the year, month and day. Use the values to create date objects, find the difference, convert to seconds and use the secondsToHMS function.
Edit
The question title mentions dates, however the content only seems to mention strings of hours, minutes and seconds.
If you have Date objects, you can get the difference between them in milliseconds using:
var diffMilliseconds = date0 - date1;
and convert to seconds:
var diffSeconds = diffMilliseconds / 1000;
and present as HH:MM:SS using the secondsToHMS function above:
secondsToHMS((date0 - date1) / 1000);
e.g.
var d0 = new Date(2014,10,10,1,43,28);
var d1 = new Date(2014,10,10,12,22,46);
console.log( secondsToHMS((d0 - d1) / 1000)); // -10:39:18
I think there is a simpler solution.
function dateDiffToString(a, b){
// make checks to make sure a and b are not null
// and that they are date | integers types
diff = Math.abs(a - b);
ms = diff % 1000;
diff = (diff - ms) / 1000
ss = diff % 60;
diff = (diff - ss) / 60
mm = diff % 60;
diff = (diff - mm) / 60
hh = diff % 24;
days = (diff - hh) / 24
return days + ":" + hh+":"+mm+":"+ss+"."+ms;
}
var today = new Date()
var yest = new Date()
yest = yest.setDate(today.getDate()-1)
console.log(dateDiffToString(yest, today))
const dateDiffToString = (a, b) => {
let diff = Math.abs(a - b);
let ms = diff % 1000;
diff = (diff - ms) / 1000;
let s = diff % 60;
diff = (diff - s) / 60;
let m = diff % 60;
diff = (diff - m) / 60;
let h = diff;
let ss = s <= 9 && s >= 0 ? `0${s}` : s;
let mm = m <= 9 && m >= 0 ? `0${m}` : m;
let hh = h <= 9 && h >= 0 ? `0${h}` : h;
return hh + ':' + mm + ':' + ss;
};
This may be the simple answer
var d1 = new Date(2014,10,11,1,43,28);
var d2 = new Date(2014,10,11,2,53,58);
var date = new Date(d2-d1);
var hour = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var day = date.getUTCDate() - 1;
console.log(day + ":" + hour + ":" + min + ":" + sec)
More intuitive and easier to read.
function hmsToSeconds(t) {
const [hours, minutes, seconds] = t.split(':')
return Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds)
}
function secondsToHMS(secs) {
return new Date(secs * 1000).toISOString().substr(11, 8)
}
var startTime = '01:43:28';
var endTime = '12:22:46';
console.log(secondsToHMS(hmsToSeconds(endTime) - hmsToSeconds(startTime))); //10:39:18

how to convert the minutes into hours and minutes with subtracted time(subtracted time values)

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/

Javascript: Adding digits without Sum?

I'm basically trying to get the hours, minutes, and seconds of a date in javascript to read like this: '123456'. I am doing this with the following code:
var date;
date = new Date();
var time = date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
Only problem is when I add them together, I keep getting the sum, not a nice line of 6 numbers like I want.
Any Suggestions?
var time = '' + date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
edit:
To account for zero-padding you can do something like:
function format(x){
if (x < 10) return '0' + x;
return x;
}
var date;
date = new Date();
var time = '' + format(date.getUTCHours()) + format(date.getUTCMinutes()) + format(date.getUTCSeconds());
Convert the numerical value to a string:
var date;
date = new Date();
var time = date.getUTCHours().toString() + date.getUTCMinutes().toString() + date.getUTCSeconds().toString();
If you want it to always be 6 characters long, you need to pad the values if they are < 10. For example:
var hours = date.getUTCHours();
if (hours < 10)
hours = '0' + hours.toString();
else hours = hours.toString();
var mins = date.getUTCMinutes();
if (mins < 10)
mins = '0' + mins.toString();
else mins = mins.toString();
var secs = date.getUTCSeconds();
if (secs < 10)
secs = '0' + secs.toString();
else secs = secs.toString();
var time = hours + mins + secs;
That's happening because those functions return an Integer type. If you want to add the digits themself togheter, try converting every variable to string using toString()

Categories