Operations 4 min read

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.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Master Bash Time Arithmetic: Add, Subtract, and Compute Date Differences

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   # 631126861

Convert the interval to seconds

time2=$((1*60*60 + 20*60))   # 1 hour 20 minutes = 4800 seconds
echo $time2   # 4800

Add the timestamps

time1=$((time1 + time2))
echo $time1   # 631131661

Convert back to a readable date

date -d "@${time1}" '+%Y-%m-%d %H:%M:%S'
# 1990-01-01 02:21:01

Time 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 dates

Convert the result to larger units if needed

echo $((timeDiff / 60))      # minutes
echo $((timeDiff / 3600))    # hours

Shell arithmetic operators

Arithmetic expansion $(( )) evaluates expressions. Example:

a=$((1+2))
echo $a   # 3

expr command provides equivalent functionality in older shells. Example:

a=$(expr 1 + 2)
echo $a   # 3
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

timestampShellUnixBashdatetime arithmetic
Liangxu Linux
Written by

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.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.