[英]Getting the same day this week in php
我正在執行一項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的同一天。
我還是通過獲取舊日期和今天之間的時間間隔差異來使用時間間隔,還是有更好的方法呢?
我建議不要使用字符串,而要使用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
進行數學運算是否正確,是否經過測試,可能是相反的情況)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.