Suppose I have a particular date stored in a variable
date_m. I want
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.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
With the GNU implementation of
date, to display yesterday's date, enter:
$ date --date="1 days ago"
$ date --date="-1 day"
For your question:
$ date --date="25 days ago"
$ 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"
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"
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