PHP为一周中的每一天生成时间戳

时间:2016-03-05 10:53:30

标签: php

我试图为一周中的每一天生成时间戳。我的一周从周一开始,结束了太阳。

到目前为止,我的代码如下。问题是今天(星期六),太阳的生成时间戳是"最后一个星期天",但它应该是"接下来的星期日"。

如果不使用if / else语句,我不确定最好的方法是什么。

$today = time();
    //$today = strtotime('next monday');

    // If today is monday, generate timestamps for each day of the week starting today
    if(date('D', $today) == 'Mon') {
        $mon = $today;
        $tue = strtotime('next tuesday');
        $wed = strtotime('next wednesday');
        $thu = strtotime('next thursday');
        $fri = strtotime('next friday');
        $sat = strtotime('next saturday');
        $sun = strtotime('next sunday');
    }
    // Today is not monday, so generate timestamps for each day of the week, starting last monday
    else {
        $mon = strtotime('last monday');
        $tue = (date('D', $today) == 'Tue') ? $today : strtotime('last tuesday');
        $wed = (date('D', $today) == 'Wed') ? $today : strtotime('last wednesday');
        $thu = (date('D', $today) == 'Thu') ? $today : strtotime('last thursday');
        $fri = (date('D', $today) == 'Fri') ? $today : strtotime('last friday');
        $sat = (date('D', $today) == 'Sat') ? $today : strtotime('last saturday');
        $sun = (date('D', $today) == 'Sun') ? $today : strtotime('last sunday');
    }

1 个答案:

答案 0 :(得分:1)

$now = time();

if(date('D', $now) == 'Mon') {
    $mon = mktime(0,0,0);
} else {
    $mon = strtotime('last monday');
}
$tue = strtotime('+1 day', $mon);
$wed = strtotime('+1 day', $tue);
$thu = strtotime('+1 day', $wed);
$fri = strtotime('+1 day', $thu);
$sat = strtotime('+1 day', $fri);
$sun = strtotime('+1 day', $sat);