普通网友 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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀