Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting Dates in Unix

Tags:

date

unix

ksh

is there a way to subtract a month from a date or at least 30 days in unix.

example:

[yyy-mm-dd] - 30 days

2011-07-23 - 30 days

By the way, the date can be any date depending on the user input.

Thanks.

like image 377
Erin Santos Avatar asked Sep 11 '25 18:09

Erin Santos


1 Answers

For an arbitrary date,

$ date -d "2011-07-23 - 1 month" "+%F"
2011-06-23
$ date -d "2011-07-23 - 30 days" "+%F"
2011-06-23
$ date -d "2011-08-23 - 1 month" "+%F"
2011-07-23
$ date -d "2011-08-23 - 30 days" "+%F"
2011-07-24

This is GNU date


Without GNU date, you can fall back to perl. The Time::Piece and Time::Seconds module should be available in perl 5.12

perl -MTime::Piece -MTime::Seconds -e '
    print "date\t-1 month\t-30 days\n";
    while (@ARGV) {
        my $t = Time::Piece->strptime(shift, "%Y-%m-%d");
        print $t->ymd, "\t";
        print $t->add_months(-1)->ymd, "\t";
        $t -= 30*ONE_DAY; 
        print $t->ymd, "\n";
    }
' 2011-07-23 2011-08-23
date    -1 month    -30 days
2011-07-23  2011-06-23  2011-06-23
2011-08-23  2011-07-23  2011-07-24
like image 81
glenn jackman Avatar answered Sep 15 '25 20:09

glenn jackman