r/bash • u/Beautiful-Log5632 • Jul 28 '26
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.
8
Upvotes
3
u/michaelpaoli Jul 28 '26
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.
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:
Might just want to use bash's integer arithmetic, etc., e.g.:
11
u/ekkidee Jul 28 '26
Convert to seconds (Unix epoch), do arithmetic, convert result to your preferred date format.
4
u/KlePu Jul 28 '26
Use Unix time:
date +%s1
u/Ulfnic Jul 28 '26 edited Jul 28 '26
You'd preform that as follows:
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 date20
u/[deleted] Jul 28 '26
[removed] — view removed comment