Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script shell how to add x minutes to a given date?

Tags:

bash

shell

I need to add 10 minutes to a given date :

givenDate = 2016-10-25 18:22:37

when executing :

newDate=$(date +'%Y-%m-%d %T' --date="$givenDate + 10 minutes")
echo $newDate

I get :

2016-10-25 00:10:00

instead of

2016-10-25 18:32:37

2nd question: How can I round the minutes number so I can get these results per exemple:

18:08 -> 18:10

18:32 -> 18:40

18:46 -> 18:50

18:55 -> 19:00

Thank you.

like image 638
slama Avatar asked Sep 01 '25 22:09

slama


1 Answers

for the first question drop the + like this:

date +'%Y-%m-%d %T' --date="$givenDate 10 minutes"

for the second question we have to extract the last digit of current minutes, then compute the number of minutes to add to make it round using modulo 5:

givenDate="2016-10-25 18:22:37"

minute=$(echo $givenDate | sed 's/.*\([0-9]\):..$/\1/')
rounder=$((5 - minute % 5))
date +'%Y-%m-%d %T' --date="$givenDate $rounder minutes"

note that the seconds haven't been taken into account

like image 117
Jean-François Fabre Avatar answered Sep 03 '25 13:09

Jean-François Fabre