简体   繁体   中英

php convert weekday to date

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 (eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM