How to get a time minus 60 minutes?

Hello,

date --date '-60 min ago' +'%Y-%m-%d %H:%M:%S,%3N'

Above command gives the date and time minus 60 minutes

but the problem i am facing is, i do not want to hardcode the value 60
it is stored in a variable var=60

now if i run below command , i get error

date --date '-$var min ago' +'%Y-%m-%d %H:%M:%S,%3N'

date: invalid date `-$var min ago'

Please suggest

Shell variables are not expanded when they appear inside a single-quoted string. Use double quotes instead of single quotes:

date --date "-$var min ago" +'%Y-%m-%d %H:%M:%S,%3N'
1 Like

Hello Ramneekgupta91,

I think you should remove - from command -60 min ago so only it will give time and date before 60 mins else it is giving 60 mins after time(you could take it as a maths concept of -ve * -ve = +ve kind of). Because you are already using keyword ago and then you are mentioning value -60 mins ago , so it will print value after 60 mins.
Here is what is the difference between -60 mins ago and 60 mins ago.

Current time:

date +'%Y-%m-%d %H:%M:%S,%3N'
2016-08-24 04:38:14,141

Using -60 mins ago :

date --date '-60 min ago' +'%Y-%m-%d %H:%M:%S,%3N'
2016-08-24 05:38:31,415

Using only 60 mins ago :

date --date '60 min ago' +'%Y-%m-%d %H:%M:%S,%3N'
2016-08-24 03:38:34,060

Now for taking values from a variable following may help you in same.

var=60   ##You could assign any value as per your need here.
date --date ''"$var"' min ago' +'%Y-%m-%d %H:%M:%S,%3N'

Thanks,
R. Singh

4 Likes

Thank you very much