1833767 Members
2148 Online
110063 Solutions
New Discussion

date X months ago

 
SOLVED
Go to solution
Alex Lavrov
Regular Advisor

date X months ago

Hello!

Just wanted to ask, not to invent the wheel again, what is the *shortest* way in shell script to get date X months ago?
If today is 2003/09/21, I want to get 2003/06/21?

thanx!
5 REPLIES 5
Steven E. Protter
Exalted Contributor
Solution

Re: date X months ago

This script will work.

It is the prior version of a great script from A. Clay Stephenson.

More current versions available on merijn's site which I have not bookmarked.

SEP
Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com
john korterman
Honored Contributor

Re: date X months ago

Hi,


It could be my browser, but the famous caljd.sh posted by Stephen Protter is unreadable over here. However, it should be the easiest thing to search for in this forum.
caljd.sh accepts various parameters for e.g. asking for the date 90 days ago, as in this example:
# PREV90=$(caljd.sh -y -s $(caljd.sh -p 90))
# echo $PREV90
20030623

but I dont think that you can supply a number of months as parameter. If months ago is 2 and today is 2003/04/30. What would then be the correct answer?

regards,
John K.
it would be nice if you always got a second chance
Rajeev  Shukla
Honored Contributor

Re: date X months ago

Hi Alex,

Here is a simple C program i wrote to get date say X days back. It can be modified to get date in the desired format and needs a input variable as day.
Say you want to get date 3 days back you run it as
a.out 3
(a.out is the compiled program)
#include
#include
#include
#include
#include
int tm, day, tm1;
char *date, *dat;
main(argc, argv)
int argc;
char *argv[];
{
time(&tm);
day=atoi(argv[1]);
day=(day*24*60*60);
date = ctime(&tm);
printf("The Present Date & Time is : %s", date);
tm1=(tm - day);
dat = ctime(&tm1);
printf("The Date & Time %s days Back was: %s", argv[1],dat);
}

Cheers
Rajeev
Stuart Browne
Honored Contributor

Re: date X months ago

If all else fails there's always GNU's date, which allows you to pass it plain-english strings for periods of difference:

gnu_date -d "3 months ago"
One long-haired git at your service...
A. Clay Stephenson
Acclaimed Contributor

Re: date X months ago

What you are asking requires a bit more thought. It's rather easy to do ninety days ago but 3 months ago, even with Gnu date, is somewhat ambiguous. Consider the case of 3 months prior to 30-May-2003; that would naturally be 30-Feb-2003, right? You need to define the rules a bit better and then a good answer can emerge.
If it ain't broke, I can fix that.