LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Looping #date -d 'last Thursday' (https://www.linuxquestions.org/questions/programming-9/looping-date-d-last-thursday-875992/)

PopEDX 04-19-2011 06:02 PM

Looping #date -d 'last Thursday'
 
I need to loop a perl script backwards in time through the dates of all Thursdays for the past few years.

I can easily get the date of last Thursday with
`date -d 'last Thursday'`

How can I get the date of the Thursday before that and so on?

I can't change the date of the System.

jlinkels 04-19-2011 06:42 PM

For calculations like this, change to Unix timestamp, or seconds.

First get the TS of last Thursday in seconds:
last_th=$(date -d "last Thursday" "+%s")
When you have that, substract 7 * 86400 seconds from it
before_last_th=$last_th-7*86400
Get the date of that day:
date -d "1970-01-01 +$before_last_th seconds" "+%F %Ts"

BTW, date is a shell command, does it exist in Perl as well? The substraction is pseudo code, adjust to your language.

jlinkels

PopEDX 04-19-2011 06:59 PM

I'm not sure if this is standard, but in my perl environment I can run shell commands like:
@array_of_directory_contents = `ls .`;

With the ` ticks.

Thank you for the info, I had the idea of doing it all in epoch time, but it seemed like a hassle.

jlinkels 04-19-2011 08:10 PM

Perl does have its date/time functions, don't know if you can get something fancy like "last thursday" without complicated loops. Using the shell command seems a good idea.

Whatever, for calculations like this, using epoch time is definitely not a hassle. I wrote a complicated project in PHP which involved nothing but schedules and time calculations. I started out using datetime formats, but later I used used exclusively epoch time in calculations. Only at the presentation end I did a conversion to or from datetime.

jlinkels

whk 04-26-2011 10:24 AM

In bash you can do this
 
This should give you a head start.
If you want years before 1970 try this.

yr=$(( 1969+28 ))
subdate=1969
yr=$(( $subdate+28 ))
mo=0$(( 1 ))
da=0$(( 2 ))

date -d $yr$mo$da +%u' '%a' '%b' '%d' '$subdate
4 Thu Jan 02 1969

The solar cycle is usually every 28 years.
Well, you know what to do when days amd months are larger than 9.
heh
a=$( echo $( date -d $yr$mo$da +%u ))
if [ $a == 4 ]
then
echo $( date -d $yr$mo$da +%u' '%a' '%b' '%d' '$subdate )
fi

hth


All times are GMT -5. The time now is 02:29 PM.