How can I add and subtract time values with date?

August 5, 2026 3 answers
Asked by MellowPine47
I want to use the date command to adjust a clock time by adding and subtracting hours, minutes, and seconds, without having time zones affect the calculation. For example, starting with 21:00:00, I want to add 2:02:30 and subtract 1:10, producing 23:01:20. What is the best way to do this?

Answers

CobaltRaven8
With GNU date, write the adjustments as explicit relative units rather than HH:MM:SS values. This produces the expected result: `date -d '21:00:00 2 hours 2 minutes 30 seconds 1 minute ago 10 seconds ago' +%T` โ†’ `23:01:20`. If you mean one minute and ten seconds, write both units explicitly; `-01:10` may be interpreted as hours and minutes instead.

QuietLime62: This syntax is GNU date-specific. POSIX date does not provide the same relative-date parsing, so check which implementation is installed before relying on it.

Reply to this answer
AmberKite5
Another option is to convert the times to Unix timestamps, do the arithmetic, and convert the result back with `date -d @SECONDS +%T`. Set `TZ=UTC` or another fixed-offset zone if you want the calculation to ignore local daylight-saving rules. For example: `TZ=UTC date -d '21:00:00 2 hours 2 minutes 30 seconds 1 minute ago 10 seconds ago' +%T`.
Reply to this answer
SilverMaple31
For portable and predictable arithmetic, convert each value to seconds, perform integer arithmetic, then format the result back into hours, minutes, and seconds. For example: `s=$((3600*(21+2)+60*(0+2-1)+(0+30-10))); printf '%02d:%02d:%02dn' $((s/3600%24)) $((s/60%60)) $((s%60))` prints `23:01:20`. This avoids date parsing and time-zone or daylight-saving surprises.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions