Differences between revisions 1 and 2
Revision 1 as of 2010-01-05 21:18:21
Size: 1051
Editor: static-200-71-6-99
Comment: irc2samus
Revision 2 as of 2010-01-06 14:04:45
Size: 1165
Editor: GreyCat
Comment: clarify
Deletions are marked like this. Additions are marked like this.
Line 3: Line 3:
Use the `date` command to parse the dates into timestamps and work on those: Using GNU `date`, first parse the dates into timestamps and work on those:
Line 6: Line 6:
# get the seconds passed since 2010 # get the seconds passed since 2010 (localtime)
Line 10: Line 10:
to print that as a human-readable value you'll have to do some math: To print that as a human-readable value you'll have to do some math:
Line 26: Line 26:
to parse the timestamp back to a readable date you need GNU date: To parse the timestamp back to a readable date, using GNU `date`:
Line 29: Line 29:
# get a date that is 90 days into the future (GNU date only) # get a date that is 90 days into the future (recent GNU date)
Line 33: Line 33:
(See [[BashFAQ/070|FAQ #70]] for more about converting Unix timestamps into human-readable dates.)

How to get the difference between two dates

Using GNU date, first parse the dates into timestamps and work on those:

# get the seconds passed since 2010 (localtime)
echo $(($(date +%s) - $(date -d "2010-01-01 00:00:00" +%s)))

To print that as a human-readable value you'll have to do some math:

# some constants
minute_secs=60 hour_secs=$((60 * minute_secs)) day_secs=$((24 * hour_secs))
# get total
seconds_since=$(($(date +%s) - $(date -d "2010-01-01 00:00:00" +%s)))
# parse
days=$((seconds_since / day_secs))
hours=$((seconds_since % day_secs / hour_secs))
minutes=$((seconds_since % day_secs % hour_secs / minute_secs))
seconds=$((seconds_since % day_secs % hour_secs % minute_secs))
# pretty-print
echo "$days days, $hours hours, $minutes minutes and $seconds seconds."

To parse the timestamp back to a readable date, using GNU date:

# get a date that is 90 days into the future (recent GNU date)
date -d "@$(($(date +%s) + 60 * 60 * 24 * 90))"

(See FAQ #70 for more about converting Unix timestamps into human-readable dates.)


CategoryShell

BashFAQ/102 (last edited 2014-12-19 21:07:32 by BinaryZebra)