Building a Work-Hours Calculator? Time Arithmetic Is the Trap
If you have ever built a timesheet tool, a shift planner, or a payroll helper, you know the feature looks trivial until you write the first test. Start time minus end time, minus a break, times an hourly rate. What could go wrong? Plenty — and almost all of it comes from treating time like ordinary decimal numbers. This article walks through the four traps that bite every work-hours calculator,…
When developing a work-hours calculator, there are four common pitfalls developers encounter. To avoid these issues, follow a few key steps. First, store times as minutes since midnight rather than as decimal numbers. This avoids problems with floating-point arithmetic causing rounding errors. Convert all time inputs to minutes using a function like `toMinutes`.
Second, perform all calculations using integers by subtracting breaks in minutes before any rounding takes place. Only round once at the end to display the final result. Third, for overnight shifts, use modular arithmetic to wrap the time difference around a 24-hour day. Fourth, validate your calculator with concrete test cases covering all scenarios, including bi-weekly paychecks and overnight shifts.
Test the calculator's state when first loaded as well, ensuring all displayed numbers are consistent. Following these steps will ensure your calculator reliably produces the correct results.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.