skip to Main Content

So for my to-do list, im trying to show in my view the difference in number of days between the current date and the date that the task is suppose to be completed by. But i cant seem to do that because im using date_diff() function and it only accepts objects and not strings for the data types.

This is the error message

date_diff(): Argument #1 ($baseObject) must be of type DateTimeInterface, string given

This is my controller

public function saveItem(Request $request) {

        $newTask = new task;

        if ($request->task == null) {
            abort(404);
        }

            $newTask->tasks = $request->task; 
            $newTask->is_complete = 0;
            $newTask->task_date = date("Y-m-d");
            
            if($request->day === "tomorrow") {

                $date = date_create(date("Y-m-d"));
                date_add($date, date_interval_create_from_date_string("1 day"));
                $newTask->date_of_completion = date_format($date, "Y-m-d");
                
            } elseif($request->day === "today") {

                $newTask->date_of_completion = date("Y-m-d");
            }
            
            $newTask->save();
            return redirect('/');

    }

This is my view

<p class="flex items-center px-4 py-1 rounded-lg text-[#555]">{{ date_diff(date("Y-m-d"), date_create($task->date_of_completion)) }}</p>

If i can find out how to change or use something else to get the current date as an object so that it can be used in my date_diff(), it will really help but if you have a better solution that is much easier, im open it to it as well.

3

Answers


  1. date_diff need DateTimeInterface type for the first parameters, in your code, you send it a string. date("Y-m-d") will return current date with format Y-m-d.

    To solve it, you just need to change your code into:

    date_diff(new DateTime, date_create($task->date_of_completion))
    

    Maybe for easier to use, you can take a look for Carbon

    Login or Signup to reply.
  2. Add date_of_completion field to $casts property, so it can be cast to a Carbon instance (https://laravel.com/docs/9.x/eloquent-mutators#date-casting).

    Then, simply call $task->date_of_completion->diffForHumans() and it calculates that for you (https://carbon.nesbot.com/docs/#api-humandiff).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search