Could someone help me with the code I need to calculate the amount of time worked using the following fields:
Hi, Juanita .
Can someone start work in the evening and finish sometime the next day or is the start time and end time always within the same day?
The next day possibility made this a little more complicated. There may be a more elegant way to do this - with fewer lines of code, but this code will accomplish the task. The idea here is to get the values of the two time picker elements into datetime objects, that can then be used to do the datetime arithmetic. You will probably want to tweak this a little. It looks like you have a date picker element too. I just used the current date and stuffed the time values into those.
export function CalculateButton_click(event) {
let cTime1 = $w('#timePicker1').value, cTime2 = $w('#timePicker2').value;
let dDate = new Date();
let YearValue = dDate.getFullYear();
let MonthValue = dDate.getMonth();
let DayValue = dDate.getDate();
let HourValue1 = Number(cTime1.substr(0,2));
let MinuteValue1 = Number(cTime1.substr(3,2));
let DateTime1 = new Date(YearValue,MonthValue,DayValue,HourValue1,MinuteValue1,0,0);
let HourValue2 = Number(cTime2.substr(0,2));
let MinuteValue2 = Number(cTime2.substr(3,2));
// it's the next day in the second dropdown if it's AM and first dropdown is PM. Add a day.
DayValue = ((HourValue2 < 12 && HourValue1 >= 12) ? DayValue + 1: DayValue);
let DateTime2 = new Date(YearValue,MonthValue,DayValue,HourValue2,MinuteValue2,0,0);
// Subtracting DateTime values returns a value in milliseconds. 60,000 milliseconds/minute.
let TotMinutesWorked = (DateTime2 - DateTime1)/60000;
let HoursWorked = Math.floor(TotMinutesWorked/60)
let MinutesWorked = TotMinutesWorked % 60; // gets remainder
let TimeWorked = HoursWorked.toString() + " hrs " +MinutesWorked.toString() + " mins";
$w('#input1').value = TimeWorked;
}
@tony-brunsman Can I get a ‘woot-woot’??? LOL!! Thank you SOOOOO much!!!
@tony-brunsman Hi!
Can you tell me all this without 2 datepickers? (like just calculate the time, without dates)
and after that it’s possible to save the worked hours in the database, in field key “total”?
thank you!
@daniel-curchi30 This example uses timePickers that returns time values in the text format hh:mm:ss.ms. For example 1:30 PM would be 13:30:00.000. I used the JS substr function to parse that out.
Having said that, I don’t think that I’m adequately answering your question. Maybe you could tell me more about what you’re trying to do. Are you going to present a form to collect the starting and ending time similar to what Juanita did?
Meanwhile, you might read up on how to work with date objects in Javascript . Understanding that is the key to doing date and time arithmetic.