Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Is there a way in unix to subtract a month or at least 30 days from a specific date? The date is to be inputted by the user.

Example:

2012-11-19 - 1 month = 2013-10-19

This one doesn't work:

date -d '2013-10-13 - 1 month' '+%F'
share|improve this question
    
Unfortunately, there is no portable tool to do date arithmetic. I think your best bet is to implement date arithmetic in ksh (and I know there is code on the web for that). –  Gilles Oct 5 '13 at 14:39

3 Answers 3

The easiest way is to convert the date to a unix time_t value (i.e. seconds since the beginning of the epoch, or '1-1-1970 00:00:00'), and then substract 30 days * 86400 seconds per day from that number.

e.g. the following example uses set -x so that you can see the value of the D variable as it changes.

#! /bin/ksh

set -x

D=$(date -d '2013-10-13' '+%s')
D=$((D - 30 * 86400))

date -d "@$D"

Note that this depends on the GNU version of date, from GNU Coreutils. Other versions of date may not support converting a time_t value back to a formatted date with @. Unless you have installed GNU coreutils, this probably isn't available on your AIX system so gawk is probably your best option to convert back to a formatted date:

echo "$D" | gawk '{print strftime("%c", $0)}'

my original answer here suggested plain awk, but further testing on my debian system has revealed that neither mawk nor original-awk have the strftime function built-in, so you'll have to install either GNU Coreutils or GNU Awk.

If perl is installed on the system, perl can be used instead of awk:

echo $D | perl -nE 'say scalar gmtime $_'

There are several alternative methods and examples of doing this at:

http://stackoverflow.com/questions/3249827/convert-from-unixtime-at-command-line

share|improve this answer

Try this:

date --date="$(date -d "Nov 1 2012")-1 month" +'%Y:%m:%d'
2012:10:01

Nov 1 2012 is used for illustration. That can be of any user input date.

share|improve this answer

Your example uses relative items in date strings which are a GNU date extension.

For example on Fedora 19 your example works as expected:

$ date -d '2013-10-13 - 1 month' '+%F'
2013-09-13

Thus, you can make sure that your script uses GNU date.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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