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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题