tags:

views:

1629

answers:

5

I think its possible but i cant come up with the right algorithm for it.

What i wanted to do was:

If today is monday feb 2 2009, how would i know the date of last week's tuesday? Using that same code 2 days after, i would find the same date of last week's tuesday with the current date being wednesday, feb 4 2009.

+7  A: 

PHP actually makes this really easy:

echo strtotime('last Tuesday');

http://uk2.php.net/strtotime

Jack Sleight
T.T why haven't i seen that in the documentation T.Tthanks a lot i owe you
lock
+6  A: 

I know there is an accepted answer already, but imho it does not meet the second requirement that was asked for. In the above case, strtotime would yield yesterday if used on a wednesday. So, just to be exact you would still need to check for this:

$tuesday = strtotime('last Tuesday');
// check if we need to go back in time one more week
$tuesday = date('W', $tuesday)==date('W') ? $tuesday-7*86400 : $tuesday;


As davil pointed out in his comment, this was kind of a quick-shot of mine. The above calculation will be off by one once a year due to daylight saving time. The good-enough solution would be:

$tuesday = date('W', $tuesday)==date('W') ? $tuesday-7*86400+7200 : $tuesday;

If you need the time to be 0:00h, you'll need some extra effort of course.

cg
This won't work 1 week per year when Sunday only has 23 hours due to DST switching (the resulting timestamp will be for Monday 23:00). Replace "7*86400" with "7*86400 + 7200". Of course in that case the time will not always be 0:00, but the date will be DST safe!
davil
You're right, this was kind of a quick-shot. Thanks for pointing that out!
cg
thanks for that, i didn't notice it until today (its wednesday now)T_T i owe you more now hehe
lock
A: 

you forgot strtotime for second argument of date('W', $tuesday) hmm.

convert $tuesday to timestamp before "$tuesday-7*86400+7200"

mde.

A: 

Working solution:

$z = date("Y-m-d", strtotime("last Saturday"));
$z = (date('W', strtotime($z)) == date('W')) ? (strtotime($z)-7*86400+7200) : strtotime($z);
print date("Y-m-d", $z);
A: 

Any idea on how to get date of last Saturday (or any other day) in MySQL?

Debiprasad