7

Suppose I have a particular date stored in a variable date_m. I want ((date_m)-25) date.

For example: I have 15/09/2014 stored in my variable , then I want 21/08/2014 returned if I subtract 25 from the date stored in variable.

12

With the GNU implementation of date, to display yesterday's date, enter:

$ date --date="1 days ago"

OR

$ date --date="-1 day"

For your question:

$ date --date="25 days ago"

OR

$ date --date="-25 day"

For using it with variables, you can use $():

pastDate=$(date --date="-25 day")
echo "$pastDate"

For general case n days and for a specific date:

#!/bin/bash
date1="Tue Sep 2 07:53:47 EEST 2014"
echo "Before? "
read n
date --date="$date1 -$n day"

Source

  • GNU date does not parse 15/09/2014 as a valid date though. – Kusalananda Jun 27 '18 at 19:16
1

In the following the date and number of days are declared.

The script turns the dates in seconds and computes what timepoint 1 (Tp1) is if the number of days (in seconds) is subtracted from the given timepoint 2 (Tp2). In the end seconds is converted back in date.

Date_m=2014/09/15
Days=25
Seconds=$(echo "$Days"*60*60*24| bc -l)
Tp2date=$(date -d "$Date_m" +%Y/%m/%d)
Tp2sec=$(date -d "$TD" +%s)
Tp1sec=$(echo "$TDsec"-"$Seconds"| bc -l)
Tp1date=$(date -d @$Tp1sec)
echo "$Tp1date"
  • The format of the date is 15/09/2014, not with the year first. – Kusalananda Jun 27 '18 at 19:17
0

Somewhat belatedly, here is one way to handle non-US dd/mm/yyyy format dates with the 25 day relative adjustment:

date_m='15/09/2014'
date --date "$(IFS=/ read d m y <<<"$date_m"; echo "$m/$d/$y - 25 days")" +%d/%m/%Y

21/08/2014

It does assume a shell such as bash that's capable of handling a string redirection <<<, and GNU date.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.