Ubuntu – Seconds, minutes and hours since a date

bashdatescripts

I would like to create a script that tells you how many seconds, minutes and hours have passed since a date (much like the +%s date command format). How can I subtract the current date with a specific date?
For example: how many seconds, minutes and hours have passed since 4th of July 1776.

Best Answer

Here's one way to do it:

time=$(($(date -d"1776-07-04 00:00:00" +%s) - $(date +%s)))

sets a time variable you can use like so:

echo $time
-7595723059

The +%s tells date to format to seconds since 1970-01-01 00:00:00 UTC which helps give us a starting point for doing the math in seconds.

Now it can also be added to a script with the same variables.

:~$ time=$(($(date -d"1776-07-04 00:00:00" +%s) - $(date +%s)))
:~$ printf '%dh:%dm:%ds\n' $(($time/3600)) $(($time%3600/60)) $(($time%60))
-2109923h:-12m:-55s

If you want Years:Days:Hours:Minutes:Seconds since, it would be the following:

printf '%dy:%dd:%dh:%dm:%ds\n' $(($time/60/60/24/365)) $(($time/60/60/24%365)) $(($time/3600%24)) $(($time%3600/60)) $(($time%60))

Which would give you output like the following:

:~$ time=$(($(date -d"1776-07-04 00:00:00" +%s) - $(date +%s)))
:~$ printf '%dy:%dd:%dh:%dm:%ds\n' $(($time/60/60/24/365)) $(($time/60/60/24%365)) $(($time/3600%24)) $(($time%3600/60)) $(($time%60))
-242y:-11d:-7h:-46m:-37s

Hope this helps!