subtract days from a date in bash

LinuxBashShell

Linux Problem Overview


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

Linux Solutions


Solution 1 - Linux

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)

Solution 2 - Linux

one liner for mac os x:

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

Solution 3 - Linux

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

Solution 4 - Linux

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

Solution 5 - Linux

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

Solution 6 - Linux

Here is my solution:

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

Solution 7 - Linux

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShivam AgrawalView Question on Stackoverflow
Solution 1 - LinuxdevnullView Answer on Stackoverflow
Solution 2 - LinuxJeremyView Answer on Stackoverflow
Solution 3 - LinuxAnkit BhardwajView Answer on Stackoverflow
Solution 4 - LinuxJutoView Answer on Stackoverflow
Solution 5 - LinuxPaweł DulębaView Answer on Stackoverflow
Solution 6 - LinuxJosé Roberto RivasView Answer on Stackoverflow
Solution 7 - Linuxuser1940175View Answer on Stackoverflow