Suppose todays' date is formatted to YYYYMMDDHHMMSS such as 20160720152654. I would want to add hours or minutes or seconds to date.
Add 1 hour should change date to 20160720162654
Add 1 minute should change date to 20160720152754
Add 1 second should change date to 20160720152655
This seems to give me incorrect results
d=date +%Y%m%d%H%M%S
pd=$(($d + ($d % (15 * 60))))
echo $d
echo $pd
Output
20160720155141
20160720155482
You can manipulate input to pass it to date -d
:
s='20160720162654'
# add 1 minute
date -d "${s:0:8} ${s:8:2}:${s:10:2}:${s:12:2} +1 min" '+%Y%m%d%H%M%S'
20160720112754
# add 1 sec
date -d "${s:0:8} ${s:8:2}:${s:10:2}:${s:12:2} +1 sec" '+%Y%m%d%H%M%S'
20160720112655
# add 1 hour
date -d "${s:0:8} ${s:8:2}:${s:10:2}:${s:12:2} +1 hour" '+%Y%m%d%H%M%S'
20160720122654
Minor addition to anubhava's answer:
Since the timezone info is not available in YYYYMMDDHHMMSS, you may get unexpected results depending on your actual timezone, such as:
s=20190201140000
date -d "${s:0:8} ${s:8:2}:${s:10:2}:${s:12:2} +1 minute" '+%Y%m%d%H%M%S'
20190201160100
# !? was expecting 20190201140100
As far as I could understand, this happens because of the +1 minute
expression, which causes date
to ignore your current timezone:
date
Thu Feb 7 17:07:28 +03 2019
date -d "20190207 17:07" "+%Y%m%d%H%M%S"
20190207170700
date -d "20190207 17:07 + 1 minute" "+%Y%m%d%H%M%S"
20190207190800
In my case, the timezone offset was +3, so that was causing problems:
date +%Z
+03
You should be able to make it work on all timezones, by adding the current timezone to the "-d" parameter:
s=20190201140000
date -d "${s:0:8} ${s:8:2}:${s:10:2}:${s:12:2} $(date +%Z) +1 minute" '+%Y%m%d%H%M'
20190201140100
Note 1 : All above commands are run on RHEL 7.4 & GNU bash, version 4.2.46(2)-release
Note 2 : I am sure there must be an easier way :)