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>
Related
How to convert milliseconds to more than 24 hours format? I am using Dayjs library but I could not figure out how to make the time format more than 24 hours.
In the code snippet below, the display should be 45:00:00.
For some reasons the output is not properly displaying on the code snippet so I also added it on jsfiddle.
dayjs.extend(dayjs_plugin_duration)
const dates = [
{
start: 1674748800000,
end: 1674831600000
},
{
start: 1674748800000,
end: 1674828000000
}
]
const totalEachDate = []
dates.filter( date => {
const dayjsStart = dayjs( date.start )
const dayjsEnd = dayjs( date.end )
const total = dayjs.duration( dayjsEnd.diff( dayjsStart ) ).$ms
totalEachDate.push( total ) // output: 23:00:00 and 22:00:00
} )
const addDates = totalEachDate.reduce( ( total, num ) => dayjs( total ) + dayjs( num ), 0 )
console.log( dayjs.duration( addDates ))
// this will display an object
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/plugin/duration.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs#1/dayjs.min.js"></script>
To convert milliseconds to hours greater than 24 hours, you can use the Dayjs library and perform a simple calculation to convert the milliseconds to hours, minutes, and seconds.You can then display the results as a string using a template expression.
Here is the code that performs the conversion :
const totalMilliseconds = addDates
const totalSeconds = Math.floor(totalMilliseconds / 1000)
const totalMinutes = Math.floor(totalSeconds / 60)
const totalHours = Math.floor(totalMinutes / 60)
console.log(`${totalHours}:${totalMinutes % 60}:${totalSeconds % 60}`)
Adds zeros for the display of hours, minutes, and seconds.
console.log(`${("0" + totalHours).slice(-2)}:${("0" + (totalMinutes % 60)).slice(-2)}:${("0" + (totalSeconds % 60)).slice(-2)}`)
I'm trying to edit following code to get the output I want.
function zoo_countdown_end_day() {
if ($('.zoo-get-order-notice .end-of-day')[0]) {
var offset = $('.end-of-day').data('timezone');
var day = new Date();
var utc = day.getTime() + (day.getTimezoneOffset() * 60000);
let d = new Date(utc + (3600000*offset)),
duration = 60 * (60 - d.getMinutes());
let timer = duration, minutes;
let hours = (23 - d.getHours());//kumudu edited this
hours = hours < 10 ? '0' + hours : hours;
let label_h = $('.zoo-get-order-notice .end-of-day').data('hours');
let label_m = $('.zoo-get-order-notice .end-of-day').data('minutes');
setInterval(function () {
minutes = parseInt(timer / 60, 10);
minutes = minutes < 10 ? "1" + minutes : minutes;
$('.zoo-get-order-notice .end-of-day').text(hours + ' ' + label_h + ' ' + minutes + ' ' + label_m);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
}
zoo_countdown_end_day();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="zoo-get-order-notice">
<span class="end-of-day"
data-timezone="+3"
data-hours="1"
data-minutes="3"></span>
</div>
This is the current output:
I just want to edit countdown time to countdown from next day 4.00 P.M (hours and minuets). Because I offer next day shipping.
Ok, the long and short of this answer is that it uses 2 functions to help..
countDown: this function takes in a functionwhileCountingDown, a numberforHowLong, then another functionwhenFinishedThen
whileCountingDown being triggered EACH second with the parameter being the amount of time left in seconds
forHowLong is the amount of seconds this countdown will last
whenFinishedThen is a function that activates AFTER the countdown is over.. it can be anything(like making a new countdown as well)
timeParse: this function takes in a numberseconds and then returns a string that looks like a more human version of time
eg: timeParse(108010), 108010 is 30 hours and 10 seconds, and it would return "1 day, 6 hours, 0 minutes"
The combination of these functions are able to have a countdown system working very well.. I ALSO DO NOT KNOW WHERE YOU GET YOUR FUTURE TIME FROM,
but if you get it in a timestamp format(like 1611860671302, a value that I copied from new Date().getTime() as I was typing this),
the line where you see 30*3600, replace that line with ((dateStamp-new Date().getTime())/1000).toFixed(0)
//honestly I don't even see where it's counting down from so i just made a countdown function that works in seconds and scheduled 30 hours from now(from when you run code).. just the format would probably need changing(since i don't know what format you want)
function zoo_countdown_end_day() {
var elem=$('.zoo-get-order-notice .end-of-day')[0]
//like I said, I didn't even see where you're taking the future time from but I'll just give a future time the equivalent of +30 hours
countDown(
(t)=>elem.innerText=timeParse(t), //every second, remaining time shows in specified element
30*3600, //seconds equivalent for 30 hours.. if you have a future dateStamp, before the countdown function, let dateStamp=this datestamp you would have, THEN change this line to.. ((dateStamp-new Date().getTime())/1000).toFixed(0)
()=>console.log("Timer Complete")
)
}
zoo_countdown_end_day();
//...............................................................
//time parsing function(takes in seconds and returns a string of a formatted date[this is what can change to change the look])
function timeParse(seconds){
var words=[
(num)=>{if(num==1){return("second")}return("seconds")},//this would return a word for seconds
(num)=>{if(num==1){return("minute")}return("minutes")},//this would return a word for minutes
(num)=>{if(num==1){return("hour")}return("hours")},//this would return a word for hours
(num)=>{if(num==1){return("day")}return("days")}//this would return a word for days
]
var timeArr=[seconds]
if(timeArr[0]>=60){//if seconds >= 1 minute
timeArr.unshift(Math.floor(timeArr[0]/60))
timeArr[1]=timeArr[1]%60
if(timeArr[0]>=60){//if minutes >= 1 hour
timeArr.unshift(Math.floor(timeArr[0]/60))
timeArr[1]=timeArr[1]%60
if(timeArr[0]>=24){//if hours >= 1 day
timeArr.unshift(Math.floor(timeArr[0]/24))
timeArr[1]=timeArr[1]%24
}
}
}
timeArr=timeArr.reverse()
.map((a,i)=>`${a} ${words[i](a)}`)
.reverse() //puts words to values and then reverses it back to correct order
timeArr.splice(timeArr.length-1,1) //takes out seconds part from being returned leaving days, minutes and hours
return(timeArr.join(', ')) //a mixture/combination of the forEach formatting(joining numbers with words), what is returned from words array and how they're joined contributes to the formatted look
}
//...............................................................
//countDown function(that works in seconds)
function countDown(whileCountingDown, forHowLong, whenFinishedThen){
//basic run down is, whileCountingDown is a function, forHowLong is a number, whenFinishedThen is a function
//in depth run down is:
/*
whileCountingDown(with parameter of how much time left in seconds) is activated every second until forHowLong seconds has passed, then whenFinishedThen is triggered
*/
var i=setInterval(()=>{forHowLong--
if(forHowLong<=0){//count finished, determine what happens next
clearInterval(i); whenFinishedThen()
}
else{whileCountingDown(forHowLong)}//do this for each second of countdown
},1000)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="zoo-get-order-notice">
<span class="end-of-day"
data-timezone="+3"
data-hours="1"
data-minutes="3"></span>
</div>
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));
I am currently working with hours as numbers, such as 2230 being equivalent to 22:30. I would like to be able to add numbers to it and sum as if they were minutes added to hours
2030 + 60 = 2130 //and not 2090
2330 + 120 = 0230 //and not 2350
Is there a library or function to doing this? Or perhaps I should change the way I am handling hours?
I don't recommend doing this, but if you want to do it, you have to handle the fact that you're pretending an hour is 100 minutes. You do that by extracting the real hours and minutes from the fake value, doing the math on them, and then reassembling them, something along these lines:
function toHoursAndMinutes(value) {
// Get hours: `value` divided by 100
const hours = Math.floor(value / 100);
// Get minutes: the remainder of dividing by 100
const minutes = value % 100;
// Return them
return [hours, minutes];
}
function fromHoursAndMinutes(hours, minutes) {
// Reassemble the number where hours are worth 100
return hours * 100 + minutes;
}
function add(a, b) {
// Get `a`'s hours and minutes
const [ahours, aminutes] = toHoursAndMinutes(a);
// Get `b`'s
const [bhours, bminutes] = toHoursAndMinutes(b);
// Add the hours together, plus any from adding the minutes
const hours = ahours + bhours + Math.floor((aminutes + bminutes) / 60);
// Add the minutes together, ignoring extra hours
const minutes = (aminutes + bminutes) % 60;
// Reassemble
return fromHoursAndMinutes(hours, minutes);
}
Live Example:
function toHoursAndMinutes(value) {
// Get hours: `value` divided by 100
const hours = Math.floor(value / 100);
// Get minutes: the remainder of dividing by 100
const minutes = value % 100;
// Return them
return [hours, minutes];
}
function fromHoursAndMinutes(hours, minutes) {
// Reassemble the number where hours are worth 100
return hours * 100 + minutes;
}
function add(a, b) {
// Get `a`'s hours and minutes
const [ahours, aminutes] = toHoursAndMinutes(a);
// Get `b`'s
const [bhours, bminutes] = toHoursAndMinutes(b);
// Add the hours together, plus any from adding the minutes
// The % 24 wraps around
const hours = (ahours + bhours + Math.floor((aminutes + bminutes) / 60)) % 24;
// Add the minutes together, ignoring extra hours
const minutes = (aminutes + bminutes) % 60;
// Reassemble
return fromHoursAndMinutes(hours, minutes);
}
console.log(add(2030, 60));
console.log(add(2330, 120));
But again, I don't recommend this. Instead, work with time values (Date or just milliseconds-since-the-Epoch, etc.) and convert for display when you need to display it.
Note that 50 rather than 0250, for two reasons: 1. 2330 + 120 is 2450 which is 00:50, not 02:50, and numbers don't have leading spaces except in string representations.
Here's my implementation of it
function add(current, time) {
const hours = Math.floor(time / 60);
const minutes = time % 60;
const currentMinutes = parseInt(current.toString().slice(2));
const currentHours = parseInt(current.toString().slice(0, 2));
const newMinutes = (currentMinutes + minutes) % 60;
const additionalHours = (currentMinutes + minutes) > 60 ? 1 : 0;
const newHours = (currentHours + hours + additionalHours) % 24;
return `${newHours < 10 ? '0' : ''}${newHours}${newMinutes < 10 ? '0' : ''}${newMinutes}`;
}
console.log(add(2030, 60)); // 2130
console.log(add(2330, 120)); // 0130
here is the working code for your clock.
var nowTime = '2350'; //current time in String..
var newMin = 120; // min you want to add in int..
var tMinutes = parseInt(nowTime.toString().slice(2)); //taking out the min
var tHours = parseInt(nowTime.toString().slice(0, 2)); //taking out the hr
var newMinutes = (newMin + tMinutes) % 60;
var newHr = tHours + parseInt(((newMin + tMinutes) / 60));
var newTime = `${newHr >= 24 ? newHr-24 : newHr}${newMinutes}`;
newTime = newTime.length < 4 ? '0'+newTime : newTime;
console.log(newTime);
If you want to handle date math, a library is probably best, because date math is hard, and the source of so many bugs if done wrong. Now, knowing how to do date math is a great thing to learn though, and reading through the source code of date math libraries is a good way to do that. Luxon is a good library with duration objects that can do what you need easily, and has readable source code. Other duration libraries also exist, so take a look at a few of those and see what you like the best. You can also abuse he built-in Date library to act like a duration object, but I don't think that's worth it.
But libraries aside, let's analyze the problem and what you might want to consider in solving it.
First off, I would say your first problem is trying to use a data type that isn't designed for what you want. A single integer is not a good idea for representing two values with different units. That is sort of what T.J. meant when he said it's a presentation concept. You have one object, but it's not really an integer in behavior. And date is close, but not quite right. So let's make a class. Duration seems like a good name:
class Duration { … }
We know it has two parts, hours and minutes. Also, it seems a good idea to just use one unit and convert them. (You wouldn't have to, but it actually makes the math easier if you do the conversion):
class Duration {
constructor ({hours = 0, minutes = 0}) {
this.totalMinutes = hours * 60 + minutes
}
}
Now lets make some getters to get just the minutes section and the hours section:
class Duration {
…
// just minutes that don't fit in hours
get minutes () { return this.totalMinutes % 60 }
get hours () { return Math.floor(this.totalMinutes / 60) }
// and also let's present it as the string you wanted:
asDisplayString() { return `${this.hours*100 + this.minutes}` }
}
Now we need to add them together. Some languages would let you use + for this, but javascript has limits on what we can make + do, so we'll add our own method. Note that because of how our constructor works, we can have more than 60 minutes when we initialize the values. Is this a good idea? Maybe. Depends on how you want the object to behave. (While we'll go with it for this example, there are definite arguments against it, mostly because it is a bit confusing that get minutes doesn't return over 60 - but it's also makes a certain sense at the same time).
class Duration {
…
add (otherDuration) {
return new Duration({minutes: this.totalMinutes + otherDuration.totalMinutes})
}
}
And now we can add our duration objects together, and the math is taken care of for us.
class Duration {
constructor ({hours = 0, minutes = 0}) {
this.totalMinutes = hours * 60 + minutes
}
// just minutes that don't fit in hours
get minutes () { return this.totalMinutes % 60 }
get hours () { return Math.floor(this.totalMinutes / 60) }
// and also let's present it as the string you wanted:
asDisplayString() { return `${this.hours*100 + this.minutes}` }
add (otherDuration) {
return new Duration({minutes: this.totalMinutes + otherDuration.totalMinutes})
}
}
d1 = new Duration({hours:20, minutes: 30})
d2 = new Duration({minutes: 50})
console.log(d1.asDisplayString(), '+', d2.asDisplayString(), '=', d1.add(d2).asDisplayString())
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);
}