普通网友 2016-03-05 10:53
浏览 71
已采纳

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

I'm trying to generate a timestamp for each day of the week. My week starts Mon and ends Sun.

My code so far is below. Problem is that today (Sat), the generated timestamp for Sun is "last sunday", but it should be "next sunday".

I'm not sure what the best way is without using loads of if / else statements.

$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条回答 默认 最新

  • dongyingjiu0669 2016-03-05 11:21
    关注
    $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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题