本周在php中获得同一天

时间:2015-10-19 05:47:06

标签: php date

我正在运行一个cron作业,将任务日期更改为当前周。目前我通过取日期并将其移动1周来更改日期。

当前控制器代码:

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);

    }
}

以上代码采用2015/10/14上周的日期,并将日期更改为本周的2015/10/21同一工作日。

现在我需要记录过去的任何日期,并将其更改为当前日期与原始日期相同的日期。所以2015/09/09应该改为2015/10/21本周的同一天。

我是否仍然通过获取旧日期和今天之间的间隔差异来使用间隔,还是有更好的方法来实现它?

1 个答案:

答案 0 :(得分:0)

我建议不要使用字符串,而是使用DateTime类:

    $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"));

(现在不要使用$diff的数学是否合适,未经过测试,可能是相反的方式)