Master Bash Time Arithmetic: Add, Subtract, and Compute Date Differences
This guide explains how to perform time addition and calculate time differences in Bash by converting dates to Unix timestamps, adjusting with arithmetic, and converting results back to readable format, including examples and shell arithmetic operator notes.
Background
When writing shell scripts, date and time calculations such as adding intervals or computing the difference between two timestamps can be performed using Unix timestamps and arithmetic expansion.
Time addition
Convert the base date to a Unix timestamp
time1=$(date +%s -d '1990-01-01 01:01:01')
echo $time1 # 631126861Convert the interval to seconds
time2=$((1*60*60 + 20*60)) # 1 hour 20 minutes = 4800 seconds
echo $time2 # 4800Add the timestamps
time1=$((time1 + time2))
echo $time1 # 631131661Convert back to a readable date
date -d "@${time1}" '+%Y-%m-%d %H:%M:%S'
# 1990-01-01 02:21:01Time difference calculation
Convert each date to a Unix timestamp and subtract
timeDiff=$(( $(date +%s -d '2010-01-01') - $(date +%s -d '2009-01-01 11:11:11') ))
echo $timeDiff # seconds between the two datesConvert the result to larger units if needed
echo $((timeDiff / 60)) # minutes
echo $((timeDiff / 3600)) # hoursShell arithmetic operators
Arithmetic expansion $(( )) evaluates expressions. Example:
a=$((1+2))
echo $a # 3expr command provides equivalent functionality in older shells. Example:
a=$(expr 1 + 2)
echo $a # 3Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
