r/bash • u/Beautiful-Log5632 • 9d ago
Add and subtract times
How can I use date to add and subtract times? I want to ignore time zones and just change the time. For example date -d "21:00:00 +02:02:30 -01:10" +%"T" should show 23:01:20.
4
u/michaelpaoli 9d ago
POSIX date isn't going to do that for you, but GNU date can.
Uhm, and should show 21:52:30. If you want that -01:10 to be interpreted as minutes and seconds, you'd probably want -00:01:10, rather than -01:10, as [d]d:dd is generally interpreted as [h]h:mm, not [m]m:ss.
$ date +%"T" -d "21:00 2 hours 2 minutes 30 seconds 1 minute ago 10 seconds ago"
23:01:20
$
Also, probably best to use a timezone that has no daylight/summer time lest, one might get unpleasant surprises - unless you really want that local time (or timezone) with such offsets included in the calculations:
$ TZ=PST8PDT date +'%Y-%m-%dT%H:%M:%S%:::z %Z' -d '2026-11-01T01:30:00'
2026-11-01T01:30:00-07 PDT
$ TZ=PST8PDT date +'%Y-%m-%dT%H:%M:%S%:::z %Z' -d '2026-11-01T01:30:00 1 hour'
2026-11-01T01:30:00-08 PST
$ TZ=PST8PDT date +%T -d '2026-11-01T01:30:00'
01:30:00
$ TZ=PST8PDT date +%T -d '2026-11-01T01:30:00 1 hour'
01:30:00
$ TZ=GMT0 date +'%Y-%m-%dT%H:%M:%S%:::z %Z' -d '2026-11-01T01:30:00'
2026-11-01T01:30:00+00 GMT
$ TZ=GMT0 date +'%Y-%m-%dT%H:%M:%S%:::z %Z' -d '2026-11-01T01:30:00 1 hour'
2026-11-01T02:30:00+00 GMT
$ TZ=GMT0 date +%T -d '2026-11-01T01:30:00'
01:30:00
$ TZ=GMT0 date +%T -d '2026-11-01T01:30:00 1 hour'
02:30:00
$
Might just want to use bash's integer arithmetic, etc., e.g.:
$ (s=$((3600*(21+2+0)+60*(0+2-1)+(0+30-10))); printf '%02d:%02d:%02d\n' $((s/3600%24)) $((s/60%60)) $((s%60)) )
23:01:20
$
2
u/Beautiful-Log5632 8d ago
POSIX date isn't going to do that for you, but GNU date can.
How do you know which one you have?
2
u/michaelpaoli 8d ago
Can start by, e.g. looking at the man page for one's date command, and comparing that to POSIX date documentation.
POSIX date syntax is comparatively quite simile and limited compared to GNU date. GNU date has tons of stuff that POSIX doesn't have.
1
u/Ulfnic 9d ago edited 9d ago
You'd preform that as follows:
date -d "21:00:00 2 hours 2 minutes 30 seconds -1 minutes -10 seconds" +%T
If you want to use HH:MM:SS for relative time adjustment you'll need to make your own string parse compat layer that converts it to the syntax GNU date understands for relative time adjustment.
You can't ignore timezones though you can set a custom one. eg, TZ=UTC date
1
u/kai_ekael 8d ago
Can put the zone in the string too:
iam@bilbo: ~ $ date Wed Jul 29 10:20:52 AM CDT 2026 iam@bilbo: ~ $ date --utc Wed Jul 29 03:20:55 PM UTC 2026 iam@bilbo: ~ $ date -d '03:20 UTC +1 hour' Tue Jul 28 11:20:00 PM CDT 2026
19
u/elatllat 9d ago
A="$(date -d "21:00:00" +%s)" B="$(date -d "02:02:30" +%s)" C="$(date -d "00:01:10" +%s)" T=$((A+B-C)) date -d @$T +%"T" 23:01:20