tags:

views:

283

answers:

7

Hi,

I need to find the date of Monday in the current week, whats the best way of doing this in php 4?

Thanks, Ben

+1  A: 
echo date('Y-m-d', strtotime('previous monday'));

Just one note, though. You want to make sure that it's not monday today, otherwise you will get date of previous monday, just like it says. You could do it as follows

if (date('w') == 1)
{
    // today is monday
}
else
{
    // find last monday
}
mr.b
This gives a date of one week ago if today is a Monday.
nickf
@nickf: see updated answer. I remembered that after I posted.. :)
mr.b
Careful with the verbiage you use with strtotime, 'previous monday' will get you a week ago on mondays, when you would really want the current day. IIRC, this week in php means monday thru sunday, but if you were to apply your answer to finding the date of tuesday for example then this would give you the wrong result on both monday and tuesday.
Kevin
@Kevin: I'm not sure I'm following you. What's precisely the difference between previous and ... last, I believe?
mr.b
+1  A: 
echo date('Y-m-d',time()+( 1 - date('w'))*24*3600);

for next week,

echo date('Y-m-d',time()+( 8 - date('w'))*24*3600);
apis17
1 for monday, 2 tuesday, 3 wednesday and so on :) have a try..
apis17
A: 

My attempt:

<?php
$weekday = date("w") - 1;
if ($weekday < 0)
{
    $weekday += 7;
}
echo "Monday this week : ", date("Y-m-d",time() - $weekday * 86400) , "\n";
?>
Greg Reynolds
+1  A: 

Try this:

return strtotime('last monday', strtotime('next sunday'));
nickf
And what if today is sunday? :)
mr.b
@mr.b - then it should still act as desired (assuming Sunday is the start of the week)
nickf
A: 

Try this.

echo date('Y-m-d', strtotime('last monday', strtotime('next monday')));

It will return current date if today is monday, and will return last monday otherwise. At least it does on my PHP 5.2.4 under en_US locale.

mr.b
A: 

$thisMonday = date('l, F d, Y', time() - ((date('w')-1) * 86400) );

Edit: explanation

  • date('w') is a numeric representation of the day of the week (0=sunday, 6=saturday)
  • there are 86400 seconds in a day
  • we take the current time, and subtract (one day * (day of the week - 1))

So, if it is currently wednesday (day 3), monday is two days ago:

time() - (86400 * (3 - 1)) = time() - 86400 * 2

If it is monday (day 1), we get:

time() - (86400 * (1 - 1)) = time() - 86400 * 0 = time()

If it is sunday (day 0), monday is tomorrow.

time() - (86400 * (0 - 1)) = time() - -86400 = time() + 86400

Rob