Robin Bantjes Robin Bantjes - 5 months ago 9
PHP Question

Getting the same day this week in 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?

Answer

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)

Comments