70

I want to subtract "number of days" from a date in Bash. I am trying something like this ..

echo $dataset_date #output is 2013-08-07

echo $date_diff #output is 2   

p_dataset_date=`$dataset_date --date="-$date_diff days" +%Y-%m-%d` # Getting Error
Lii
  • 11,553
  • 8
  • 64
  • 88
Shivam Agrawal
  • 2,053
  • 4
  • 26
  • 42

7 Answers7

68

You are specifying the date incorrectly. Instead, say:

date --date="${dataset_date} -${date_diff} day" +%Y-%m-%d

If you need to store it in a variable, use $(...):

p_dataset_date=$(date --date="${dataset_date} -${date_diff} day" +%Y-%m-%d)
Zombo
  • 1
  • 62
  • 391
  • 407
devnull
  • 118,548
  • 33
  • 236
  • 227
  • 1
    I had to modify this to `$ date "--date=${dataset_date} -${date_diff} 1 day" +%Y%m%d` to actually subtract the date... otherwise it would have added one day. Is there anything i missed? – Max May 07 '14 at 15:57
  • @x_mtd Yes, you need to set the variable `date_diff`. Set it to the number of days that you want to subtract. – devnull May 07 '14 at 17:18
  • Very slight improvement to the command - date --date="${dataset_date} -${date_diff} day" +%Y-%m-%d. Just to make it clearer that the --date is an option to the date command, and the double-quotes are being used to correctly represent the STRING passed to the --date option. – anuragw Aug 24 '16 at 19:37
  • How to find the difference if dataset_date is in this format: %Y-%m-%d %H:%M:%S – Etisha Apr 30 '20 at 11:24
36

one liner for mac os x:

yesterday=$(date -d "$date -1 days" +"%Y%m%d")
Jeremy
  • 1,824
  • 14
  • 20
9

If you're not on linux, maybe mac or somewhere else, this wont work. you could check with this:

yesterday=$(date  -v-1d    +"%Y-%m-%d")

to get more details, you could also see

man date
Ankit Bhardwaj
  • 101
  • 1
  • 2
6

To me, it makes more sense if I put the options outside (easier to group), in case I will want more of them.

date -d "$dataset_date - $date_diff days" +%Y-%m-%d

Where:

 1. -d --------------------------------- options, in this case 
                                         followed need to be date 
                                         in string format (look up on $ man date)
 2. "$dataset_date - $date_diff days" -- date arithmetic, more 
                                         have a look at article by [PETER LEUNG][1]
 3. +%Y-%m-%d -------------------------- your desired format, year-month-day
Juto
  • 1,246
  • 1
  • 13
  • 24
4

Here is my solution:

echo $[$[$(date +%s)-$(date -d "2015-03-03 00:00:00" +%s)]/60/60/24]

It calculates number of days between now and 2015-03-03 00:00:00

Paweł Dulęba
  • 1,048
  • 1
  • 13
  • 25
4

Here is my solution:

today=$(date +%Y%m%d)
yesterday="$(date -d "$today - 1 days" +%Y%m%d)"
echo $today
echo $yesterday
2

Below code gives you date one day lesser

ONE=1
dataset_date=`date`
TODAY=`date -d "$dataset_date - $ONE days" +%d-%b-%G`
echo $TODAY
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94