普通网友 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 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探