jojo jojo - 4 months ago 28
Bash Question

Increment hours/minutes/seconds of date in YYYYMMDDHHMMSS using bash

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

Answer

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
Comments