php convert weekday to date

date, php, weekday

Solution

You can use `strtotime()` magic for this:

function dayDate($day) {
    return date('m-d-Y', strtotime('next ' . $day));
}

Consider using PHP's native `DateTime` class instead, though:

function dayDate($day) {
    return new DateTime('next ' . $day);
}

$nextMonday = dayDate('Monday');
echo $nextMonday->format('m-d-Y'); // 04-30-2012

Using the `DateTime` object allows you to do some pretty neat stuff, in addition to allowing you to remove the hard-coded date format from your method/function, in case you need to change it on the fly.

Problem

``` function dayDate($day) { $dayArr = array( 0 => 'MONDAY', 1 => 'TUESDAY', 2 => 'WEDNESDAY', 3 => 'THURSDAY', 4 => 'FRIDAY', 5 => 'SATURDAY', 6 => 'SUNDAY' ); $sunday = mktime(0, 0, 0, date('m'), date('d')+(1-date('w')), date('Y')); $n = array_search("$day",$dayArr); $date = date('m-d-Y', $sunday+$n*60*60*24); return $date; } ``` i am using the above function to convert a weekday (e.g. Monday) to a date of current week, i use this function in a loop and pass in $day like "SUNDAY" "MONDAY" and it returns me the date. but for some reason its missing the first Sunday. for example if its "Sunday April 22, 2012" today and i pass in SUNDAY it gives me the date of next Sunday instead of today. any help would be highly appreciated. Thanks.

Original source