I’m building an attendance tracker in PowerApps where employees can clock in and out. Some shifts start late at night (e.g., 11:14 PM) and end the following day (e.g., 6:53 PM).
I'm using the DateDiff function to calculate the total hours worked, but it’s returning incorrect values—739 hours, instead of the expected 19 hours for shifts crossing midnight.
Here’s the formula I’m using:
With(
{
varUserAttendance: Filter(
colAttendance,
Year(Created) * 12 + Month(Created) = Year(Today()) * 12 + Month(Today())
)
},
If(
CountRows(varUserAttendance) > 0,
Round(
Sum(
varUserAttendance,
DateDiff(
DateTimeValue(ShiftStartTime), // Start time
If(
DateTimeValue(ShiftEndTime) < DateTimeValue(ShiftStartTime),
DateAdd(DateTimeValue(ShiftEndTime), 1, TimeUnit.Days), // Add 1 day for cross-midnight
DateTimeValue(ShiftEndTime) // Same day
),
TimeUnit.Hours
)
),
2
) & " hour(s)",
"No records for this month"
)
)
Key Details:
What I’ve Tried So Far:
Question:
How can I correctly calculate hours worked for shifts that span midnight without encountering these errors?
Thanks in advance for any suggestions!
ClearCollect(
colAttendanceWithHours,
AddColumns(
colAttendance,
"HoursWorked",
Round(
DateDiff(
DateTimeValue(ShiftStartTime),
If(
DateTimeValue(ShiftEndTime) < DateTimeValue(ShiftStartTime),
DateAdd(DateTimeValue(ShiftEndTime), 1, TimeUnit.Days),
DateTimeValue(ShiftEndTime)
),
TimeUnit.Hours
),
2
)
)
)
The issue stems from handling shifts that span midnight correctly, particularly in how DateTimeValue
interprets the ShiftEndTime
relative to the ShiftStartTime
. Here's how you can resolve this issue:
The core logic needs to:
ShiftEndTime
is earlier than ShiftStartTime
).ShiftEndTime
by adding 1 day in such cases.ShiftStartTime
and ShiftEndTime
are parsed consistently as DateTime
values.Here’s an updated and corrected formula:
Checking for Cross-Midnight Shifts:
DateTimeValue(ShiftEndTime) < DateTimeValue(ShiftStartTime)
detects if the shift spans across midnight.ShiftEndTime
to ensure it represents the correct date and time.Parsing ShiftStartTime
and ShiftEndTime
:
DateTimeValue
is used to convert the text fields into DateTime
values. This is crucial to perform accurate time calculations.ShiftStartTime
and ShiftEndTime
) store the time in a consistent format (e.g., yyyy-MM-ddTHH:mm:ss
).Summing the Hours:
DateDiff
calculates the difference in hours between the adjusted start and end times for each record.Round and Display:
ShiftStartTime
and ShiftEndTime
are stored in a consistent time format (HH:mm:ss
or yyyy-MM-ddTHH:mm:ss
). If not, preprocess the data to standardize it.DateTimeValue(ShiftStartTime)
and DateTimeValue(ShiftEndTime)
for a specific row to ensure correct parsing.
MS.Ragavendar
20
BCBuizer
10
Super User 2025 Season 1
LC-26081402-0
10