Add seconds to a given date in bash

I have a complete date plus hours and minutes. I would like to add a number of seconds and display the result as a date "day.month.year hour:minute".

"date" doesn't seem to be able to add seconds to a given date.


Solution 1:

In fact, the GNU date command (which is the standard implementation in Ubuntu) can add date offsets directly - for example to add 3662 seconds (1hr, 1min, 2sec) to a given date

$ date '+%d.%b.%Y %T' --date="2012-06-13 09:16:16 EDT + 3662 seconds"
13.Jun.2012 10:17:18

However, some care is required with timezones and daylight savings - a safer option is probably to convert the original time into seconds since the start of the epoch, and add the desired offset to that before converting back to the desired format, e.g.

$ secs=$(date +%s --date="2012-06-13 09:16:16")
$ date '+%d.%b.%Y %T' --date="@$((secs + 3662))"
13.Jun.2012 10:17:18

Solution 2:

You can also increment the current date easily with:

date --date="+1 seconds" '+%Y-%m-%d %T'

man date says this is documented in info date, but I don't feel like reading info manuals now to quote it :-)

Tested in Ubuntu 18.04, date from Coreutils 8.28.

Solution 3:

Like this:

$ date +%x.%H:%M:%S:%N
01/21/2014_16:02:07:422856522

It shows a US styled data for me but see man date for more refinement. The 2 interesting options:

%N     nanoseconds (000000000..999999999)
%S     second (00..60)

And if you want to use the standard year, month, day format:

$ date +%Y.%m.%d_%H:%M:%S:%N
2014.07.21_16:07:52:641771706