douwei1921 2015-10-19 05:47
浏览 71
已采纳

本周在php中获得同一天

I'm running a cron job to change task dates to the current week. Currently I am changing the date by taking the date and moving it on by 1 week.

Current Controller code:

function weekly_tasks() 
{ 
    $this->load->model('tasksmodel');
    $data['weekly_tasks'] = $this->tasksmodel->get_weekly_tasks();
    var_dump($data);

    foreach ($data['weekly_tasks'] as $row) 
    {
        // change parent task date to next week
        $date = $row->due_date;
        $newdate = strtotime ( '+1 week' , strtotime ( $date ) ) ;
        $newdate = date ( 'Y-m-j' , $newdate );
        $row->due_date = $newdate;

        // set up task update var
        $task_update = $row;
        $task_id = $row->task_id;

        //create this week's task
        $task_create = $row;
        $this->tasksmodel->create_weekly_tasks($task_create);
        var_dump($task_create);


        // update the task to next week
        $this->tasksmodel->update_weekly_tasks($task_update, $task_id);

        var_dump($task_update);

    }
}

The above code takes a date last week 2015/10/14 and changes the date to the same weekday this week 2015/10/21.

Now I need to take any date in the past and change it to the same day of the current week as in the original date. So 2015/09/09 should change to the same day this week 2015/10/21.

Do I still use intervals by getting the difference in interval between old date and today or is there a better way to do it?

  • 写回答

1条回答 默认 最新

  • dongpa9277 2015-10-19 06:36
    关注

    I recommend to not to work with strings but with DateTime class:

        $date = new Date($row->due_date);
        $newdate = new Date(); // this is obviously in the "current" week.
    
        // get the week day of the "old" and "new" date:
        $oldWD = $date->format("N");
        $newWD = $newdate->format("N");
    
        // set current weeks weekday as diff of weekday:
        $diff = $oldWD - $newWD;
        if ( $diff > 0 )
            $newdate->add( new DateInterval("P" . $diff . "D") );
        else if ( $diff < 0 ) // $diff == 0 means no changes
            $newdate->sub( new DateInterval("P" . abs($diff) . "D") );
    
        // adjust times to the time of the old date
        $newdate->setTime(date->format("H"), date->format("i"), date->format("s"));
    

    (don't now whether the math with $diff is proper, not tested, probably it's the other way round)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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