Ubuntu – Add seconds to a given date in bash

bashdatescriptstime

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.

Best Answer

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