How to sum time fields javascript HH:MM - javascript

I have an adobe pdf that calculates elapsed time, which is working. I however want to sum those times to give a total time in HH:MM format. enter image description here Anyone have any ideas on the javascript code that could do this?
enter image description here

In case i understand you correctly and you have an array of eplapsedTime as text,
You can run over the values and sum the hours in left part and minutes in right with split.
const flightTimes = ['09:12','12:13','02:55','23:40','05:59'];
let hours = 0, minutes = 0;
flightTimes.forEach((time) => {
const split = time.split(':');
hours += parseInt(split[0]);
minutes += parseInt(split[1]);
});
const formattedNumber = (num) => ("0" + num).slice(-2);
hours += Math.floor(minutes/60);
minutes = minutes % 60;
console.log(formattedNumber(hours) + ':' + formattedNumber(minutes));

Related

Vue JS timepicker SUM Hours dan Minutes Calculation

I have a problem when calculating the total from the timepicker on the repeater field.
I created a function on vue js computed.
Here's the script:
https://jsfiddle.net/andreasdan/afwy6k9n/42/
This ini my calculation script:
computed: {
totalDuration: function() {
let total = 0;
this.detail_data.map( item => {
total += item.hour_timespan
})
return total;
}
},
The data I want to display is like this:
Total Duration : 23:30
Hi #Toni Rhubanaga,
You can modify your computed property like this.
First, you can loop through the detail_data array and add up the hour_timespan values, which you are already have done. Then, you could convert the total number of minutes into hours and minutes by dividing the total number of minutes by 60, I guess. Then, use toString() for in a string in the format HH:MM.
computed: {
totalDuration: function() {
let totalMinutes = 0;
this.detail_data.map( item => {
totalMinutes += item.hour_timespan
})
let hours = Math.floor(totalMinutes / 60);
let minutes = totalMinutes % 60;
return hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0');
}
},
Well, it converts the total number of minutes into hours and minutes, and then format the result as a string in the format. Total duration in the format HH:MM, Right.
And display the total duration in your HTML, like this.
<div>Total Duration: {{ totalDuration }}</div>

Difference between two timestamps in hours minutes and seconds

I am trying to calculate the difference between two timestamp
"2020-03-18T17:34:45.856Z", "2020-03-18T16:34:45.856Z"
the difference should be like this: 2 hours 20min 30sec
I have tried using
return moment.utc(moment(startDate, 'HH:mm:ss').diff(moment(endDate, 'HH:mm:ss'))).format('HH:mm:ss');
m not sure how to get the desired format
You need to get it manually using Moment Duration
const startDate = "2020-03-18T17:34:45.856Z";
const endDate = "2020-03-18T16:34:45.856Z";
const diff = moment(startDate).diff(moment(endDate));
const duration = moment.duration(diff);
const hrs = duration.hours();
const mins = duration.minutes();
const secs = duration.seconds();
console.log(hrs + "hours " + mins + "min " + secs + "sec");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

How to get right format in moment js

i need to convert input value: ":2" to 'HH:mm' format.
":2" it should be converted to "00:20". All this process should be done with moment.js
let timeString = ":2";
const time = document.getElementById('time');
time.innerHTML = moment(timeString).format('HH:mm');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<span id="time"></span>
I didn't put input, because my problem is to get or convert correct format.
As stated before, you will have to convert the input yourself before passing it to momentjs - the following could work for you, depending on what the result for other values should be. I assumed:
":3" -> "00:30",
":21" -> "00:21",
"2:2" -> "02:20"
let timeString = ":2";
const hours = timeString.split(":")[0] || "00";
let minutes = timeString.split(":")[1];
if (minutes.length === 1) {
minutes = minutes * 10;
}
const parsedTime = hours + ":" + minutes;
const time = document.getElementById('time');
time.innerHTML = moment(parsedTime, "HH:mm").format("HH:mm");

How to add hours to string formatted as HH:MM:SS in 24 hour format

I'm trying to add hours to time in the format of 24 hours say '23:59:59'. I need to add, for example, 2.5 hours so the time should roll to the next day and be shown as '02:30:00'.
What I have tried so far works until it reaches '23:59:59'. I need to show the next day time if it exceeds '23:59:59'. Here is what I have tried so far:
var time = $('#starttime').val().split(':');
var d = new Date();
d.setHours(+time[0]);
d.setMinutes(time[1]);
d.setSeconds(time[2]);
var time2 = $('#endtime').val().split(':');
var endtimeval = new Date();
endtimeval.setHours(+time2[0]);
endtimeval.setMinutes(time2[1]);
endtimeval.setSeconds(time2[2]);
var str = d.getHours() + parseInt($('#noofhours').val()) + ":" + time2[1] + ":" + time2[2];
$('#endtime').val(str);
Using a Date Object here is possibly unnecessary, modulo arithmetic should suffice.
const pad = n => {
const s = String(n);
return s.length > 1 ? s : '0' + s;
};
const addHours = (timeVal, numHours) => {
const [hr, min, sec] = timeVal.split(':').map(Number);
const [,lefty, righty] = String(numHours).match(/(\d+)(?:(\.\d+))?/).map(Number);
const hours = (hr + lefty) % 24;
const minutes = righty === undefined ?
min :
((righty * 60 | 0) + min) % 60;
return [hours, minutes, sec].map(pad).join(':');
};
addHours('23:59:59', 2.5) // "01:29:59"
Note that since there's no dates involved it will not accurately handle e.g. daylight savings time. Also note that minutes are in this example rounded down, you could repeat the logic for seconds if desired.
Note that your approach using Date objects will give different answers for the same inputs depending on when/where the logic runs, for the same reasons.
Make a custom date adder?
const add = (time, hours) => {
let [hh, mm, ss] = time.split(':');
const seconds = hours * 60 * 60;
ss = ss * 1 + seconds;
if (ss >= 60) {
mm = mm * 1 + ss / 60;
ss = (ss % 60).toPrecision(2).padStart(2, '0');
}
if (mm >= 60) {
hh = hh * 1 + mm / 60;
mm = (mm % 60).toPrecision(2).padStart(2, '0');
}
hh = (Math.floor(hh) % 24).toString().padStart(2, '0');
return hh + ':' + mm + ':' + ss;
}
console.log(add("23:59:59", 2.5));
you may apply DRY principle and refactor the code yourself. But it will get the job done according to your requirement.
The simple trick that I did is just converted the hours entered as float/int to a minute value by multiplying to 60 and created a date, with this just added the time I already have.
Here the solution with minimal steps:
var time = $('#endtime').val().split(':');
var d = new Date();
d.setHours(+time[0]);
d.setMinutes(time[1]);
d.setSeconds(time[2]);
var addeddate = new Date();
addeddate.setMinutes(parseFloat($('#noofhours').val()) * 60);
$('#endtime').val(("0" + (addeddate.getHours())).slice(-2) + ":" + ("0" + (addeddate.getMinutes())).slice(-2) + ":" + ("0" + (addeddate.getSeconds())).slice(-2)); //The answer that I needed in endtime id value.
You can use vanilla JavaScript Date methods fairly easily here. Most of the work is parsing the time string inputs and then concatenating the time string output. For example:
const start = '23:59:59';
const add = '2.5';
const [hh, mm, ss] = start.split(':').map(x => parseInt(x));
const d = new Date(new Date().setHours(hh, mm + (add * 60), ss));
const end = `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
console.log(end);
// 2:29:59

Moment.js adding difference between multiple dates

I am using the following code to get difference between two dates in hrs, minutes and seconds, which I will save later in database as a string field. So I was wondering if it is possible to use Moment.js library or any Javascript functionally in order to get the total number of hours, minutes and seconds for all date differences saved in the database (ex. 02:24:33 + 03:12:20 + 12:33:33) as one final HH:MM:SS taking in consideration that the HH could exceed 24 if the total number of hours summed exceeded 24? Thanks
$('.set-start-time').on("dp.change",function (e) {
$('.set-end-time').data("DateTimePicker").setMinDate(e.date);
});
$('.set-end-time').on("dp.change",function (e) {
$('.set-start-time').data("DateTimePicker").setMaxDate(e.date);
var now = $('.set-start-time').data('DateTimePicker').getDate().toLocaleString();
var then = $('.set-end-time').data('DateTimePicker').getDate().toLocaleString();
console.log(moment.utc(moment(then,"DD/MM/YYYY HH:mm:ss").diff(moment(now,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss"));
//Output here come in format ex. 02:42:33
});
It's probably too late for this to matter, but maybe something like this would help:
http://jsfiddle.net/8s8v3evf/8/
tl;dr
once you have your diff:
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
function diffAsString(diff_ms) {
var hours = Math.floor(diff_ms / 3600000);
diff_ms -= (hours * 3600000);
var minutes = Math.floor(diff_ms / 60000);
diff_ms -= (minutes * 60000);
var seconds = Math.floor(diff_ms / 1000);
return zeroPad(hours, 2) + ':' + zeroPad(minutes, 2) + ':' + zeroPad(seconds, 2);
}

Categories

Resources